This week's book giveaway is in the Design forum.
We're giving away four copies of Design for the Mind and have Victor S. Yocco on-line!
See this thread for details.
Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String.intern method

 
Manish Hatwalne
Ranch Hand
Posts: 2591
Android Firefox Browser Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2120
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Jamal Hasanov
Ranch Hand
Posts: 411
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 61
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

this would return true,as intern returns a interned string,better check JLS for intern,it could be amazing.
 
Tina Ang
Ranch Hand
Posts: 58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic