wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes String.intern method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "String.intern method" Watch "String.intern method" New topic
Author

String.intern method

Manish Hatwalne
Ranch Hand

Joined: Sep 22, 2001
Posts: 2578

When I use following code -

Is the memory allocated on heap is saved? I understand that it would add the literals to the string pool, moreover s1==s2 will result in true.
But does it really have any advantage as far as memory used to create an object (a String object in this case) is concerned? Also, where can I get to read more abt this in details besides RHE?
TIA,
- Manish
Jose Botella
Ranch Hand

Joined: Jul 03, 2001
Posts: 2120
Another advantage is speed of comparations between strings. If several strings to compare are interned, they can be compared with == which is faster than compareTo. Because == only compares that the memory address of both String objects is the same. They are the same because subsequent calls to intern simply return the same addres of a string allocated in the string pool that has the same content.


SCJP2. Please Indent your code using UBB Code
Jamal Hasanov
Ranch Hand

Joined: Jan 08, 2002
Posts: 411
Manish,
Sorry, but I didn't understood why you're using intern() in your code...? (s1==s2 will give you false) What's the advantage of this?
Jamal.
aymen esawey
Ranch Hand

Joined: Jan 29, 2002
Posts: 61

this would return true,as intern returns a interned string,better check JLS for intern,it could be amazing.


Aymen Esawey<br />SCJP <img src="smile.gif" border="0"> <br /><a href="http://www.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=32&t=001968" target="_blank" rel="nofollow">how to nuke the SUN </a>
Tina Ang
Ranch Hand

Joined: Mar 12, 2002
Posts: 58
Jamel,
If String objects having the same data are created explicitly with the new operator or their values are computed at runtime, their references will be different.
Literal strings will represent the same reference if they are created by explicitly using the intern() method and the resulting string is already in the string pool.
Tina
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: String.intern method
 
Similar Threads
problem with assigning Strings to variables
I am Confused !!!!! Pls Help
String method intern()
question regarding String.intern()
Significant different between == and equals()?