简体   繁体   English

在Java中,为什么在字节的情况下前缀递增或递减运算符不需要强制转换

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

In java Suppose i have following code snippet 在Java中假设我有以下代码片段

byte b = 127;
b=-b ;//(which require a cast due to numeric promotion)
b=++b; //does not require cast

The JLS specification of ++ says: ++的JLS规范说:

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. ....在加法之前,对值1和变量的值执行二进制数值提升(第5.6.2节)。 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. 如有必要,可通过缩小原始转换(第5.1.3节)来对和进行缩小,和/或在存储变量之前,先对变量的类型进行装箱转换(第5.1.7节)。 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 . 参考: JLS 15.15.1

Therefore ++b is a byte and no explicit cast is required. 因此, ++b是一个byte ,不需要显式强制转换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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