5

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?

1
  • possible duplicate of Java += operator Commented Nov 28, 2012 at 11:04

1 Answer 1

18

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.

Sign up to request clarification or add additional context in comments.

2 Comments

you can observe the difference when you manually write b = b + l; then you will see the error you want :-)
Sorry, b+l gives a long. And I need to read the oracle docs more. Thanks.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.