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?
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?
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