It's a common misconception that X += Y
is identical to X = X + Y
. From JLS §15.26.2:
A compound assignment expression of the form
E1 op= E2
is equivalent toE1 = (T) ((E1) op (E2))
, whereT
is the type ofE1
, except thatE1
is evaluated only once.
Notice that there is an implicit cast involved. Now when you have something like:
ch = ch + 2; // no cast, error
the type of the right-hand side is int
while the type of the left-hand side is char
, so there is a type mismatch between the two sides of the assignment, hence the error. This can be fixed with an explicit cast:
ch = (char) (ch + 2); // cast, no error