In Java, the expression:
n+++n
Appears to evaluate as equivalent to:
n++ + n
Despite the fact that +n
is a valid unary operator with higher precedence than the arithmetic +
operator in n + n
. So the compiler appears to be assuming that the operator cannot be the unary operator and resolving the expression.
However, the expression:
n++++n
Does not compile, even though there is a single valid possibility for it to be resolved as:
n++ + +n
++n
and +n
are specified as having the same precedence, so why does the compiler resolve the seeming ambiguity in n+++n
in favour of the arithmetic +
but does not do so with n++++n
?
Best Answer
The file is tokenized (transformed into sequence of tokens) first with the maximal munch rule - always get longest possible valid token. Your text is transformed to following sequence:
And this is not valid expression.
From JLS §3.2: