Why does this assignment not require an explicit cast?

casting, java, operators

Solution

Well to start with, `b+l` gives a `long`, not an `int`...

... but compound assignment operators have other behaviour. As per 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.

Note the cast to `T`.

Problem

Consider this code: ``` byte b=1; long l=1000; b += l; ``` I would expect the last statement to require an explicit cast because, `b+=l` is evaluated as `b = b+l` and `(b+l)` part gives an integer. Integer cannot be assigned to byte without an explicit cast?

Original source