-1

why s3==s4 returns false while s2==s3 returns true in line no. 8 and 7 respectively.

 1. String s="hello";`
 2. String s1="he"+"llo";
 3. String s2="hello"+123;
 4. String s3="hello123";
 5. String s4=ss+"123";

 7. System.out.println(s==s1);//prints true
 8. System.out.println(s2==s3);//prints true
 9. System.out.println(s3==s4);//prints  false
Madhawa Priyashantha
  • 9,633
  • 7
  • 33
  • 60

2 Answers2

3

s + "123"; is not compile-time evaluable so is not a candidate for string internment. (Note that if s was final then it would be.)

Therefore its reference will not be the same as s3, so the output is false.

The others all compare true due to string internment and the compile-time evaluabality of the expressions.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • I know it's a bit naughty to answer this question as there *must* be an adequate duplicate out there somewhere, but @downvoters, do tell me if there is something amiss in the answer ;-) – Bathsheba Mar 31 '16 at 12:37
0

When you use == operator to check the equality of Strings, it checks if the location of the Strings in the memory is the same.

In cases 2 and 4, the Strings "hello" and "hello123" will already be in the String Constant Pool (due to lines 1 and 3) and will be recognized as equivalent to those Strings, and will use the same place in memory for each. In simple terms, it will create a String object and plug it into both instances of "hello" and "hello123".

When you do:

String s4=s+"123";

At run time, it creates a new memory location for s4, since, the JLS says that:

Strings computed by concatenation at run-time are newly created and therefore distinct.

So, the memory locations are different, and hence it gives false as the output.

dryairship
  • 6,022
  • 4
  • 28
  • 54