What is the difference between an addition of String Literal and String Object?
For example
String s1 ="hello";
String s2 ="hello1";
String s3 ="hello" + "hello1";
String s4 ="hellohello1";
String s5 = s1 + s2;
System.out.println(s3 == s4); // returns true
System.out.println(s3 == s5); // return false
System.out.println(s4 == s5); // return false
Why do s3/s4 not point to the same location as s5?
Because
s1 + s2is not a constant expression, sinces1ands2are notfinal, therefore its result is not interned, i.e. another object is created to represent it, so reference comparison producesfalse.JLS 3.10.5 String Literals:
JLS 15.28 Constant Expression:
JLS 4.12.4 defines
finalvariables.If you declare
s1ands2asfinal,s3 == s5would betrue.