我们都知道在Java中这些运算符:
a++;
++a;
a += 1;
a = a + 1;
做同样的事情,他们只是将 1 加到变量 'a'
然而为什么这些说法并不都是真的,这背后的原理是什么?
byte a = 1;
a++;
++a;
a += 1;
a = a + 1; // This line will result to a compile time error
为什么?
最佳答案
每当您在两个不同类型的操作数之间执行二元运算时,其中一个操作数将提升为更高类型。然后操作的结果就是那个类型。
因此,在您的情况下,byte
类型 a
首先被提升为 int
,因为 1
是 int
类型。然后在加法运算之后,结果是类型int
。现在,由于您不能将 int
分配给 byte
,您需要进行类型转换以消除编译器错误:
byte a = 2;
a = a + 1; // Error: Cannot assign an int value to byte
a = (byte)(a + 1); // OK
现在,对于复合赋值运算符,类型转换是隐式为您完成的。表达式:
a += 1
内部转换为:
a = (byte)(a + 1);
这是在 JLS 中指定的 - §15.26.2 Compound Assignment Operator :
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.
前缀增量运算符和后缀增量运算符的情况类似。
根据 JLS - §15.15 Unary Operators :
The type of the prefix increment expression is the type of the variable.
关于java - 字节一元运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17607816/