-2

Suppose I have this code

public class Test{
    public static void main (String args[]) { 
        String s = "thrones";
        System.out.println("Game of" + "thrones" == s) ;
    }
}

The output of the above code block is just 'false'

But shouldn't it print 'Game of true'

However if i put a parenthesis for the ("thrones"==s), it prints properly

System.out.println("Game of" +    ("thrones"==s));

'Game of true'

I am just curious why it isn't taking the first part of the print in the first case. I just want to know whats going on there while compiling.

Thanks.

shashank
  • 47
  • 1
  • 8
  • Would `1+ 1==2` be true? (or would it give you an error saying you can't add an int and a boolean?) Spaces are ignored. – user253751 Sep 06 '15 at 22:56
  • 2
    Shouldn't it print "false"? – Svante Sep 06 '15 at 22:59
  • At least 2 potential issues: 1. You don't use `==` to compare strings in Java. 2. You obviously know you operator precedence better than me - I'd add some `()` to make it clear what your intent is... – John3136 Sep 06 '15 at 23:00
  • You have got the "precedence" part of the answer here: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html (+ is interpreted before ==) – maxime.bochon Sep 06 '15 at 23:01

1 Answers1

1

First, it really prints false, because "Game of thrones" != "thrones"!

Second, you seem to have answered your own question. It's parsing "Game of" + "thrones" == s as ("Game of" + "thrones") == s, because the + operator has a higher precedence than the == operator.

John Bupit
  • 10,406
  • 8
  • 39
  • 75