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

风格不统一 提交于 2019-12-02 22:31:53

问题


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:


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.



来源:https://stackoverflow.com/questions/28378928/in-java-why-prefix-increment-or-decrement-operator-does-not-require-cast-in-case

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!