-1

Why does this code work correctly in Java? I have tried it in Eclipse and Itellij IDEA. The result is 8.

int a = 3, b = 5; System.out.println(a + + b);

Tonton
  • 113
  • 2
  • 9
  • 8
    Hint (assuming that `a` and `b` are numeric types): `System.out.println(+1); System.out.println(-1);` – Pshemo Sep 11 '15 at 18:31
  • Another thing : 99% of the time the IDE is unrelevant to the question. Some bugs are specific to the Eclipse-compiler (or specific to a non-Eclipse compiler) but that's very rare – Dici Sep 11 '15 at 18:36

1 Answers1

1

In java, + plays many roles according to the type of variables it is acting on. For numeric variables + is a binary and also a unary operator. So in your statement

System.out.println(a + + b);

the compiler consider +b as an expression with the unary operator + (which does nothing), and then add a to that expression using the other + that is consider now as a binary operator. To better understand this, you should read about the priority of operators.

innoSPG
  • 4,588
  • 1
  • 29
  • 42