gpt4 book ai didi

java - java中的类型转换规则

转载 作者:搜寻专家 更新时间:2023-11-01 01:42:05 26 4
gpt4 key购买 nike

众所周知的事实:(byte)1 ^ (byte)1 导致 int(根据规范)。

有人可以向我解释为什么无需显式转换(从 intbyte)就可以实现以下内容吗? byte myByte = (byte)1 ^ (byte)1

另一方面,以下内容是不允许的:

int i = 0; byte b = i;

最佳答案

这个:

(byte)1 ^ (byte)1

是常量表达式 ( JLS 15.28 ),已知其在 byte 范围内。因此,您可以在赋值上下文 (JLS 5.2) 中将其隐式转换为 byte:

In addition, if the expression is a constant expression (§15.28) of type byte, short, char, or int:

  • A narrowing primitive conversion may be used if the type of the variable is byte, short, or char, and the value of the constant expression is representable in the type of the variable.

如果它不是常量表达式(例如,如果其中一个值是变量),则赋值将失败。

关于java - java中的类型转换规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31342771/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com