-1

Can you please explain me why the output is

false

instead of

abcd abc false

Code:

public class StringDemo{
    public static void main(String [] args){
        String s1 = "abc";
        String s2 = s1;
        s1+="d";
        System.out.println(s1+ " "+ s2 +" "+ s1==s2); //false
    }
}   
Yunnosch
  • 26,130
  • 9
  • 42
  • 54
  • @PradeepSimha not quite. as shown by Andy in his answer. also, it depends whether the OP is using `==` for reference equality which is valid with the `==` operator or content equality which one would need to use `equals`. – Ousmane D. Jul 14 '18 at 20:27
  • I am not sure why this question got so many downvotes. It is not about very simple and common `equals vs ==` problem (although using `equals` would solve OP problem), but about `+` (concatenation) vs `==` precedence. Duplicate question with explanation wasn't easy to find for me who already knew the answer, so I imagine that for OP who didn't know what was going on finding proper answer would be even harder. – Pshemo Jul 14 '18 at 20:42
  • It seems that you accidentally overwrote your question with a completly different one. I undid that for you. Please use the "Ask Question" button to ask a different question. Improvements of this question are welcome, but should not change it so fundamentally that the existing answer is invalidated. – Yunnosch Feb 13 '21 at 11:34
  • Asking new question has been disabled for me – Ajay Singh Meena Feb 13 '21 at 12:34

1 Answers1

7

It prints false because of the relative precedence of + and ==. + has higher precedence, so it is equivalent to:

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

so the argument to System.out.println is a boolean, not a string.

Add parentheses:

System.out.println(s1+ " "+ s2 +" "+ (s1==s2));
Andy Turner
  • 137,514
  • 11
  • 162
  • 243