-2
String s1 = "abcd5";

String s2 = "abcd"+"5";
String s3 = "adcd"+s1.length();
System.out.println("s1 == s2 : "+(s1 == s2));
System.out.println("s2 == s3 : "+(s2 == s3));
System.out.println("s1 == s3 : "+(s1 == s3));

Why first statement is true and rest are false. Is String concatenation with int behaves differently?

BackSlash
  • 21,927
  • 22
  • 96
  • 136
Smith
  • 151
  • 3
  • 11
  • Not a duplicate of that question. This question is completely different. – BackSlash Feb 03 '17 at 21:38
  • @Pshemo At least the context of the one you linked is similar, the current duplicate one has really nothing to do with this question. – BackSlash Feb 03 '17 at 21:41
  • 2
    The problem is your assignment to "s3" the string has "d" at 2nd position. Unfortunately this has been marked duplicate. So the comparison is happening with "ab..." and "ad..." so anytime there is s3 in the mix false is the right behavior – Aniruddh Dikhit Feb 03 '17 at 21:46
  • Another duplicate: [Java String literals concatenation](http://stackoverflow.com/questions/16771122/java-string-literals-concatenation) – Pshemo Feb 03 '17 at 21:52

1 Answers1

3

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.

davidxxx
  • 125,838
  • 23
  • 214
  • 215
  • 1
    got it, in case of s3, compiler is not able to decide the value hence at runtime s3 reference points to heap where "abcd5" object gets created. – Smith Feb 03 '17 at 22:04
  • s3="adcd" is a typo mistake, we all know what is the real concepts here that was discussed. – Smith Feb 04 '17 at 11:19
  • Ah Okaaay.... Indeed this little String value difference seemed strange for a trap question. – davidxxx Feb 04 '17 at 11:35