--
is a “decrement” operator in Java and many other languages. The reason the compiler doesn’t treat it as two -
operators is that there’s a basic rule that the compiler will look for the longest sequence of consecutive characters that forms one of its “separators” or “operators”, as defined here. (>
characters are handled a bit differently because of generics.)
This is explicitly stated in JLS 3.2:
The longest possible translation is used at each step, even if the
result does not ultimately make a correct program while another
lexical translation would. There is one exception [for>
characters]…
Thus, when the compiler sees --4
, it treats it as a --
operator applied to 4
, which is illegal. It doesn’t backtrack and try to find other ways to interpret the --
.
But if it sees - -4
, with a space between the hyphens, it can’t interpret the -
as anything else except individual minus signs. This is legal and has the same meaning as -(-4)
.
solved =- operator in java