In java why prefix increment or decrement operator does not require cast in case of byte

后端 未结 1 1941
醉酒成梦
醉酒成梦 2021-01-26 07:33

In java Suppose i have following code snippet

byte b = 127;
b=-b ;//(which require a cast due to numeric promotion)
b=++b; //does not require cast
1条回答
  •  借酒劲吻你
    2021-01-26 08:37

    The JLS specification of ++ says:

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

    .... Before the addition, binary numeric promotion (§5.6.2) is performed on the value 1 and the value of the variable. If necessary, the sum is narrowed by a narrowing primitive conversion (§5.1.3) and/or subjected to boxing conversion (§5.1.7) to the type of the variable before it is stored. The value of the prefix decrement expression is the value of the variable after the new value is stored.

    (The term "narrowing primitive conversion" refers to a type cast ...)

    Reference: JLS 15.15.1.

    Therefore ++b is a byte and no explicit cast is required.

    0 讨论(0)
提交回复
热议问题