FMC FMC - 1 year ago 73
Java Question

Why does this not compile

I am trying to play with Java to understand operator precedence. Based on what I have read I think the following code should work:

System.out.println(("" + (1--2)));

I believe it should be evaluated in this order:

  • (1--2) becomes 3

  • ("" + 3) becomes "3"

  • System.out.println("3")

So I expect it to print 3 but it does not appear to be legal code. Can someone explain where I am going wrong with this?

Answer Source

You need to type it like so:

System.out.println(("" + (1-(-2))))

"--" is not recognized as a valid operator in this instance so it's causing a compiler error. Also, it will return 3, not -1.

Edit: As mentioned, another way to type it is with a space in between the "-" like so:

System.out.println(("" + (1 - -2)))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download