We’ve been learning since we first printed “hello world” that
i += 1
expands to
i = i + 1
Well, here’s a little problem to shake the faith.
byte i = 1;
i = i + 1;
System.out.println(i);
Being java programmers worth our salt, it wouldnt take much to identify the compilation error.
Error: Possible loss of precision
So how do we explain that the next code snippet prints the value 2?
byte i =1;
i += 1;
System.out.println(i);
Here’s the secret: i += 1 is not same as i = i + 1 When you do an assignment (the first code snippet), java enforces type checking because the LHS and RHS may very well be independent of each other. But the compound-operator is more like an incremental operator. The += modifies the value of the variable involved, rather than assigning a new value to the variable. When you modify a byte, you expect a byte as the result. To make life easier, java does an implicit type conversion for compound-operators because they are modifiers.
Have fun!