It is not necessary to use brackets. Both prefix and postfix ++
have a higher precedence than +
.
However, it is necessary to use something to separate the ++
and +
operators. If you don't separate them (with whitespace, comments or other tokens) you get a rather confused compilation error. For example:
Test.java:3: error: unexpected type
int j = i +++++ i;
^
required: variable
found: value
1 error
Here's what is going on:
The lexical analyser reads the above as int j = i ++ ++ + i ;
. This is a consequence of 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."
Taking precedence into account, the parser parses the expression as:
+
/ \
++ i
/
++
/
i
where ++
is the postfix increment operator. That is equivalent to ((i++)++) + i
.
The analyser detects that postfix ++
is being applied to the result of i++
, which is a value. That is illegal. The operand of ++
has to be variable not a value.
As JLS 15.14.2 says:
"The result of the [operand] must be a variable of a type that is convertible to a numeric type, or a compile-time error occurs."
But seriously, don't write code like this. It is just confusing ... and unnecessary.