在java中,为什么前缀增量或减量运算符在字节的情况下不需要强制转换 [英] In java why prefix increment or decrement operator does not require cast in case of byte

查看:108
本文介绍了在java中,为什么前缀增量或减量运算符在字节的情况下不需要强制转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在java中假设我有以下代码片段

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


推荐答案

++ 说:


前缀增量表达式的类型是变量。

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

....在添加之前,对值1和变量值执行二进制数字提升(第5.6.2节)。 如果需要,在存储之前,通过缩小基元转换(第5.1.3节)和/或对变量类型进行限制转换(第5.1.7节)来缩小总和。前缀减量表达式的值是存储新值后变量的值。

.... 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 ...)

参考: JLS 15.15.1

因此 ++ b 字节,不需要显式强制转换。

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

这篇关于在java中,为什么前缀增量或减量运算符在字节的情况下不需要强制转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆