This is regarding the difference in the result returned by '+' operator. Result varies for String literal and String Object.
String str="ab";
String str1="c";
String str2 = "ab"+"c"; // Line 3
String str3 = "abc";
String str4 = str+str1; // Line 5
System.out.println(str2==str3); // True
System.out.println(str2==str4); // False
With the result we can deduce that with literal, already available object from the string pool is returned as in case of line 3 and with string object new object is returned, as in line 5. Why is it so?
The +
oprator for String
s is handled differently depending on the time when the expression can be evaluated.
When the expression can be evaluated at compile time (as in line 3) the compiler will create a String
containing only the concatenation. Therefore in line 3 only the String
"abc" will be created and this String
will be put in the .class file. Therefore str3
and str4
will be exactly the same and will be interned.
When using a concatenation that can be evaluated only at runtime (as in line 5) the resulting String
is a new String
which must be compared wth equals()
as it is a new object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With