0

I'm definitely missing something

public static void main(String []args){
    String s1 = "abc";
    String s2 = "abc";
    System.out.println(s1 ==  s2);//gives true
}

public static void main(String []args){
    String s1 = "abc";
    String s2 = "abc";
    System.out.println("s1 == s2 is:" + s1 ==  s2); //gives false
 }

something to do with operator precedence??

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
  • 4
    On a side note, don't compare Strings with `==`, use `equals(String)` or `equalsIgnoreCase(String)` – Rogue Feb 05 '14 at 18:33
  • 1
    Although in this case, it _would_ work as expected if you added the parentheses, since you're comparing string constants (which are guaranteed by JLS to be `==` if they're `equals`). – yshavit Feb 05 '14 at 18:37
  • Note to those who will answer "don't use `==` to compare Strings": it looks as though that's the intended behavior, an investigation of (interned) String constants in Java. – Reinstate Monica -- notmaynard Feb 05 '14 at 18:48

5 Answers5

7

Yes, the + operator is of higher precedence than ==, so you are comparing the string "s1 == s2 is:abc" to "abc". You can always use parentheses to force an explicit order of operations.

rgettman
  • 176,041
  • 30
  • 275
  • 357
2

Yup. It's evaluated as:

("s1 == s2 is:" + s1) ==  s2
yshavit
  • 42,327
  • 7
  • 87
  • 124
1

As answered by others Yes '+' operator has more precedence then the '=='. If you enclose the comparison within parenthesis like

   System.out.println("s1 == s2 is"+(s1 == s2)); 

The above statement will give true since parenthesis is having higher precedence than +.

If you feel why string s1 and s2 are referring to the same memory location then it is because of string literal pool concept.

Srikanth Ganji
  • 1,127
  • 1
  • 13
  • 29
0

+ opertator has higher precidence then == so you are doing "s1 == s2 is:abc" to "abc".

Note that use equal or equalIgnoreCase to comparing the String always because == always compares reference

Girish
  • 1,717
  • 1
  • 18
  • 30
0

dude you are not supposed to use == for string comparison instead use equals method.

string1.equals(string2)
  • 3
    That's true in general, but it's not the answer in this case. Firstly, the operator precedence makes it a moot point; and secondly, if you fixed the operator precedence (by adding parentheses), it would print `s1 == s2 is:true` because OP is comparing string constants. – yshavit Feb 05 '14 at 18:39
  • == for string is overloaded to check underlying values. dude s1 is string NOT s1 = new String("abc") –  Feb 05 '14 at 18:52
  • This does not answer the question at all. – Sotirios Delimanolis Feb 05 '14 at 19:34
  • @user1635354 No, Strings do not overload `==`. Nothing does or can overload `==` in Java. It compares the objects for reference equality, same as it does for any reference types. – yshavit Feb 05 '14 at 19:44