EDIT :
I though having seen this code :
String s1 = "abcd5";
String s2 = "abcd"+"5";
String s3 = "abcd"+s1.length();
Whereas my first explanation :
because s1
and s2
are literal String so at compile time these have the same String value and are interned and so reference the same object.
while s3
is a String computed at runtime, so it doesn't reference the same String instance.
But in fact, the code is :
String s1 = "abcd5";
String s2 = "abcd"+"5";
String s3 = "adcd"+s1.length(); // a - d - c - d and not a - b - c - d
As @Aniruddh Dikhit has noticed (very good eyes): in your assignment to "s3"
the string has "d"
at the 2nd position and not only at the 4th position.
Consequently, whatever the way you declare s3
(with literal or not), the s3
value has not the same value as the String referenced by s1
and s2
, so it could never have the same object reference.