FMC
FMC

Reputation: 660

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:

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?

Upvotes: 0

Views: 104

Answers (2)

Crislips
Crislips

Reputation: 460

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 this is with a space in between the "-" like so:

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

Upvotes: 7

Matt
Matt

Reputation: 113

Java reads -- as a decrement operator, meaning that it needs to be attached to a variable for proper syntax, not next to a literal. You can fix this by simply putting a space in between the two -symbols, i.e. System.out.println(("" + (1- -2)));

Upvotes: 3

Related Questions