• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String Pool Vs String new operator

 
kri shan
Ranch Hand
Posts: 1478
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
String str1 = "how are you";

String str2 = new String("how are you");

Whether String Str1 will refer string poll for Str1 exists in the pool or not. If exists, then this will return the reference, If not exist, will it create new object like new operator ?
String str2 never refer the string pool because it is created by new operator(creates new String object in the heap). Which one is memory efficient ?
 
Paul Clapham
Sheriff
Posts: 21416
33
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is it more memory-efficient to use an existing object from a pool, or to create a new object which is a copy of one from the pool?
 
Campbell Ritchie
Sheriff
Pie
Posts: 50180
79
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Have you seen what it says in the API about that String constructor?
 
Rob Spoor
Sheriff
Pie
Posts: 20661
65
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Obviously the first statement is more memory efficient. Both use the same String from the String pool, but the first one uses only this object; the second one makes an exact copy of it and uses that. With String being immutable, that's completely superfluous. That's why the API discourages using that constructor, as Campbell's link indicates.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic