| Author |
String.intern method
|
Manish Hatwalne
Ranch Hand
Joined: Sep 22, 2001
Posts: 2573
|
|
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
|
 |
 |
|
|
subject: String.intern method
|
|
|