简体   繁体   中英

Primitive type casting

I have been working with Java's byte primitive lately, and I came across a silly problem:

byte a = 10;
byte b = 9;
byte c = 8;
b += b*c;    // how come this statement is correct without any explicit type casting
b =  b*c;    // while this statement is incorrect; it requires explicit cast, of course
b = b+(b*c); // this is wrong too.

So my question is, does += specify any assignment other than just add and assign, or is this a bug in Java (which I am almost sure is not)?

Because b += b*c is equivalent to b += (byte) ((b) + (b*c)) .

From the Java language specification on compound assignment operators :

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.

All compound assignment operators not only performs the operation, but also cast automatically their result to the type of the left-hand side variable.

So your += not only adds variables and assign the result - it also cast the result to the right type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM