Compound assignment operators behave a little differently than their "expanded" version. Quoting the JLS, Section 15.26.2:
A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T) ((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.
It is implicitly casted back to the type of the variable on the left side, so that there is no error casting a float
to an int
; it's already implicitly casted to an int
.
That does not occur with the =
operator, which is governed by the JLS, Section 5.2, Assignment Conversion:
Assignment contexts allow the use of one of the following:
an identity conversion (§5.1.1)
a widening primitive conversion (§5.1.2)
a widening reference conversion (§5.1.5)
a boxing conversion (§5.1.7) optionally followed by a widening reference conversion
an unboxing conversion (§5.1.8) optionally followed by a widening primitive conversion.
It goes on to talk about a possible narrowing conversion being allowed, but only for constant expressions, and only for the constant expression being a byte
, char
, short
, or int
, neither of which is applicable here.