class Test {
public static void main(String...args) {
String s1 = \"Good\";
s1 = s1 + \"morning\";
System.out.println(s1.intern());
The result code dependents runtime:
class Test {
public static void main(String... args) {
String s1 = "Good";
s1 = s1 + "morning";
System.out.println(s1 == s1.intern()); // Prints true for jdk7, false - for jdk6.
}
}
If you write like this:
class Test {
public static void main(String... args) {
String s = "GoodMorning";
String s1 = "Good";
s1 = s1 + "morning";
System.out.println(s1 == s1.intern()); // Prints false for both jdk7 and jdk6.
}
}
the reason is ' ldc #N ' (Load string from constant pool) and String.intern() both will use StringTable in hotspot JVM. For detail I wrote a pool english article: http://aprilsoft.cn/blog/post/307.html
In jdk6:
String s1="Good";
creates a String object "Good" in constant pool.
s1=s1+"morning";
creates another String object "morning" in constant pool but this time actually JVM do: s1=new StringBuffer().append(s1).append("morning").toString();
.
Now as the new
operator creates an object in heap therefore the reference in s1
is of heap not constant pool
and the String s2="Goodmorning";
creates a String object "Goodmorning" in constant pool whose reference is stored in s2
.
Therefore, if(s1==s2)
condition is false.
But what happens in jdk7?
You need to use s1.equals(s2)
. Using ==
with String
objects compares the object references themselves.
Edit: When I run your second code snippet, I do not get "both are equal" printed out.
Edit2: Clarified that references are compared when you use '=='.