我正在初始化两个整数 a
和 b
。
a
编译良好,但 b
出现错误。
public class Main_1 {
public static void main(String[] args) {
int a = -2147483648; //Working fine
int b = -(2147483648); //Compilation error: The literal 2147483648 of type int is out of range
}
}
请帮助我理解这种行为?
最佳答案
原因是 int
数据类型在 [-2147483648, 2147483647]
范围内具有有效值。
当您将 2147483648
包裹在括号内时,它会变成一个表达式,将被评估为 int
。但是,2147483648
太大而无法放入 int
(太大一倍)。
-2147483648
不会出现问题,因为它是有效的 int
值。
JLS 的相关部分:
- 添加括号会创建一个“带括号的表达式”(section 15.8.5)
- 一个整数文字,例如
2147483648
,默认被视为一个int
(section 3.10.1)An integer literal is of type
long
if it is suffixed with an ASCII letterL
orl
(ell); otherwise it is of typeint
(§4.2.1).
关于java - 括号中的整数无法编译 - 为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33752327/