Why can't Unary Operators operate directly on values in Java?

Not that I want to, but I'm wondering why the unary operators don't work directly on values in Java?

Why does result++; work if int result = 0; but result = 0++; not work?

All I can find in the docs is that the unary operator only requires one operand, but there is no clear definition for an operand, and it seems that it can be either a variable or a value.

Jon Skeet
people
quotationmark

It's not that unary operators don't work - for example -(+(-5)) is fine.

But ++ doesn't just compute a value - its purpose is to increment a variable. 0 isn't a variable.

From JLS 15.14.2 (postfix increment operator++)

The result of the postfix expression must be a variable of a type that is convertible (ยง5.1.8) to a numeric type, or a compile-time error occurs.

Note that this isn't just about literals, either. You can't do:

String x = "foo";
x.length()++; // wrong!

because again, x.length() isn't classified as a variable.

But you can use other unary operators, e.g.

String x = "foo";
int y = -x.length(); // Unary - operator... that's fine

people

See more on this question at Stackoverflow