[英]Primitive type casting
I have been working with Java's byte primitive lately, and I came across a silly problem: 我最近一直在使用Java的字节原语,我遇到了一个愚蠢的问题:
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)? 所以我的问题是,
+=
指定除了添加和赋值之外的任何赋值,或者这是Java中的错误(我几乎可以肯定不是)?
Because b += b*c
is equivalent to b += (byte) ((b) + (b*c))
. 因为
b += b*c
等于b += (byte) ((b) + (b*c))
。
From the Java language specification on compound assignment operators : 从复合赋值运算符的Java语言规范:
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.
形式E1 op = E2的复合赋值表达式等效于E1 =(T)((E1)op(E2)),其中T是E1的类型,除了E1仅被评估一次。
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. 所以你的+ =不仅添加变量并分配结果 - 它还将结果转换为正确的类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.