Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
The moose likes Java in General and the fly likes String Pool Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "String Pool" Watch "String Pool" New topic
Author

String Pool

Gagan Kinra
Greenhorn

Joined: May 14, 2012
Posts: 7
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

Joined: Jan 03, 2004
Posts: 6109
    
    6

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

Joined: May 14, 2012
Posts: 7
Thanks a lot
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

You're welcome!
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 36599
    
  16
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
 
subject: String Pool
 
Similar Threads
strings
question regarding String.intern()
strings
What the output related to string
Behaviour of + in case of String literals