gpt4 book ai didi

java - 为什么分配 'int constant -> byte variable' 有效,但 'long constant -> int variable' 无效?

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

我有这段代码:

int i = 5l; // not valid (compile error)
byte b = 5; // valid

你怎么看?

为什么?

最佳答案

这是在 the JLS #5.2 (Assignment conversion) 中定义的:

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.

所以:

byte b = 5; //ok: b is a byte and 5 is an int between -128 and 127
byte b = 1000; //not ok: 1000 is an int but is not representable as a byte (> 127)
byte b = 5L; //not ok: 5L is a long (and not a byte, short, char or int)
int i = 5L; //not ok: i is not a byte, short or char
int i = 5; byte b = i; //not ok: i is not a constant
final int i = 5; byte b = i; //ok: i is a constant and b is a byte

关于java - 为什么分配 'int constant -> byte variable' 有效,但 'long constant -> int variable' 无效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21778266/

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