Consider following snippet.
CASE #1
public class HelloWorld {
public static void main(String[] args) {
String str1 = "abc";
String str2 = "ab";
str2 = str2 + "c";
System.out.println("str1 :" + str1+ ", str2 :" + str2);
System.out.println(str1 == str2);
}
}
The result is
sh-4.3$ java -Xmx128M -Xms16M HelloWorld
str1 :abc, str2 :abc
false
Here, the result of str1 == str2
comes out to be false. However, if you use "+" operator to concatenate two literals. It gives you the address of the string literal "abc" from string constant pool. Consider following snippet
CASE #2
public class HelloWorld {
public static void main(String[] args) {
String str1 = "abc";
//String str2 = "ab";
str2 = "ab" + "c";
System.out.println("str1 :" + str1 + ", str2 :" + str2);
System.out.println(str1 == str2);
}
}
The result is
sh-4.3$ java -Xmx128M -Xms16M HelloWorld
str1 :abc, str2 :abc
true
Can someone please explain why string interning is done in CASE #2 and not in CASE #1? Why do we get 'str1==str2' as false in CASE #1 and true in CASE #2?