• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String Pool

 
Gagan Kinra
Greenhorn
Posts: 7
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a doubt regarding string pool

String s1 = "lo";
String str11 = "Hel"+ s1;
String str12 = "He" + "llo";
System.out.println(" str11 == str12 is " + (str11.intern() == str12));

Output is
======
true

but when
String s1 = "lo";
String str11 = "Hel"+ s1;
String str12 = "He" + "llo";
System.out.println(" str11 == str12 is " + (str11 == str12));

Output is
======
false


Please help in understanding this concept
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Gagan Kinra wrote:I have a doubt regarding string pool

String s1 = "lo";
String str11 = "Hel"+ s1;
String str12 = "He" + "llo";
System.out.println(" str11 == str12 is " + (str11.intern() == str12));

Output is
======
true


The line String str12 = "He" + "llo"; causes the compiler to create a String constant "Hello". Since all the pieces being concatted together are compile-time constants, the compiler can treat treat them as a single String. So, like all string literals, it goes into the constant pool.

Then we intern str11, which also has contents "Hello". The result we get back from intern() is a reference to a String in the constant pool. Since "Hello" was already there from the above steps, it's the same object, and == is true.


but when
String s1 = "lo";
String str11 = "Hel"+ s1;
String str12 = "He" + "llo";
System.out.println(" str11 == str12 is " + (str11 == str12));

Output is
======
false


Here we did not intern str11, so we're comparing a reference to a String in the pool with a reference to a String out of the pool, so two different objects, so == is false.
 
Gagan Kinra
Greenhorn
Posts: 7
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're welcome!
 
Campbell Ritchie
Sheriff
Pie
Posts: 47300
52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Look at this old JavaRanch Journal article, which I think you will find helpful.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic