0
String s5="Ram";
String s6="Ram";

System.out.println("  s5==s6  is " + s5==s6);  // false
System.out.println(s5==s6);  // true

Why the first line is false and the second line is true always?

Ramesh-X
  • 4,853
  • 6
  • 46
  • 67
attish raj
  • 19
  • 6
  • Just wanted to say, you should use .equals() to compare string values. Because == will always be false. I don't know why it is true in your 5th line. – DudeManGuy Feb 22 '19 at 06:30
  • @Thilo - you *didn't* have to reopen the question, however briefly it was. You could've added the dupe to the list. – Makoto Feb 22 '19 at 06:32
  • 1
    @Thilo: ...then you could have *removed* those dupes from the list. Again, doesn't necessitate reopening the question. – Makoto Feb 22 '19 at 06:35
  • @Thilo: Now - the dupe you linked half-answered the question. It explained precedence, but not about string interning. The dupes I had put in there explained what interning was and how it worked. – Makoto Feb 22 '19 at 06:38

1 Answers1

5

Because + has a higher precedence than ==,

" s5==s6 is "+s5==s6

evaluates as

" s5==s6 is Ram"=="Ram"

which is obviously false. You could have avoided this particular problem by using parentheses:

" s5==s6 is "+(s5==s6)

Meanwhile,

s5==s6

evaluates as

"Ram"=="Ram"

which is true only because of automatic interning of string literals in Java. If one of those strings was evaluated rather than a literal, it would be false, as == compares object identity, and two different String objects would be evaluated as different even if they had the same content. Compare

String s5 = new String("Ram");
String s6 = new String("Ram");
System.out.println(s5==s6); //false

Use .equals for meaningful comparison of string contents:

System.out.println(s5.equals(s6)); //true
Amadan
  • 191,408
  • 23
  • 240
  • 301