7

I am trying to understand the working of System.out.println() in Java... in following 2 code snippet , why the answer is different and why it do not print "Hello: " string inside println() method ?

 public static void main(String[] args) {
        String x = "abc";
        String y = "abc";
        System.out.println("Hello:" + x == y);
        System.out.println("x.equals(y): " + x.equals(y));

        if(x == y){
            System.out.println("Hello:" + x==y);
        }

}

Answer is :

false
x.equals(y): true
false

And for second code snippet :

 public static void main(String[] args) {
        String x = "abc";
        String y = "abc";

        System.out.println( x == y);

        System.out.println("x.equals(y): " + x.equals(y));

        if(x == y){
            System.out.println(x==y);
        }

}

The answer is:

true
x.equals(y): true
true
aniketk
  • 109
  • 1
  • 7

2 Answers2

12

This is due to operator precedence: "Hello:" + x == y is equivalent to ("Hello:" + x) == y.

Because + has a higher precedence than ==.

assylias
  • 321,522
  • 82
  • 660
  • 783
  • Thanks @assylias....Yes, I got it now...,,Now I put brackets around x==y and it works fine . e.g System.out.println( "Hello: " + (x == y)); – aniketk Jun 24 '16 at 08:57
2

first one is returning false because + operator has high precedency than == operator it will also return true if you replace your code
System.out.println("Hello:" + (x == y));

you can also refer for see the difference in == and equals method at here
What is the difference between == vs equals() in Java?

because i will also tell the same.

and for operator precedence see this..
http://introcs.cs.princeton.edu/java/11precedence/

Community
  • 1
  • 1
jitendra varshney
  • 3,484
  • 1
  • 21
  • 31