Consider the following Java code:
int result = 0;
for (int i = 0; i < 10; i++) {
result += 1;
}
The loop performs 10 iterations, and hence result
holds the value 10 when the loop terminates.
Now consider the following, almost identical, code:
int result = 0;
for (int i = 0; i < 10; i++) {
result =+ 1;
}
The only difference is that we now replace the valid +=
operator with =+
. The latter may look like an operator, but in fact is not (see e.g. Oracles introduction to Java operators). However, the code still compiles just fine after this change. The loop obviously still performs 10 iterations, but result
will be 1 instead of 10.
What happens here is that the +
part of =+
associates with 1
instead of the =
, so the code is essentially the same as:
int result = 0;
for (int i = 0; i < 10; i++) {
result = +1;
}
which is in turn the same as:
int result = 0;
for (int i = 0; i < 10; i++) {
result = 1;
}
It seems very plausible that a newcomer might mistakenly write =+
instead of +=
. In fact, I remember doing so myself a few years back when I started learning Java.
This behaviour is essentially caused by the fact that Java allows arbitrary whitespace (including no whitespace) between operators and operands as well as the ability to explicitly specify that a number is positive (as in result = +1;
).
Allowing arbitrary whitespace seems beneficial in the sense that you can structure your code as you like. However, what is the benefit of allowing explicit positive numbers? Obviously (and luckily) it does not turn an already negative number into a positive number:
int value = -42;
value = +value;
// value is still -42.
There must be something here that I am missing that warrants the extra confusion/headaches that newcomers may be experiencing as a result of this design decision.