有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java字节一元运算

我们都知道,在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

为什么


共 (2) 个答案

  1. # 1 楼答案

    a=a+1

    这是由于表达式的类型a = a + 1;。LHS被提升为int,然后执行加法。然后,您尝试将int值重新分配给byte而无需强制转换

    参考JLS 5.6.2

    Widening primitive conversion (§5.1.2) is applied to convert either or both operands as specified by the following rules:

    1. If either operand is of type double, the other is converted to double.

    2. Otherwise, if either operand is of type float, the other is converted to float.

    3. Otherwise, if either operand is of type long, the other is converted to long.

    4. Otherwise, both operands are converted to type int.

    a++; ++a

    这里的类型就是变量的类型。同样按照JLS 15.15

    The type of the prefix increment expression is the type of the variable.

    The type of the prefix decrement expression is the type of the variable.

    a+=1

    根据JLS 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.

    因此这里a += 1;等同于a = (byte)(a+1);,因为它是隐式完成的

  2. # 2 楼答案

    每当在两个不同类型的操作数之间执行二进制运算时,其中一个操作数将升级为更高的类型。然后操作的结果就是这种类型

    因此,在您的例子中,byte类型a首先被提升为int,因为1int类型。然后在加法运算之后,结果是类型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.