对常量求和时隐式缩小与对变量求和时显式缩小
Implicit narrowing when summing constants vs explicit narrowing when summing variables
我写了程序
class First
{
public static void main(String[] args)
{
int c = 5;
byte b = c+6;
System.out.println(b);
}
}
我的 javac 输出是:
error: incompatible types: possible lossy conversion from int to byte
byte b = c+6;
^
1 error
但是如果我修改程序为:
class First
{
public static void main(String[] args)
{
byte b = 5+6;
System.out.println(b);
}
}
执行正常,输出:
11
我知道在操作之前,两个操作数都会转换为整数。然后 + 运算符产生一个整数。但是如果变量 c 是一个整数,那么常量 5 默认也是一个整数。为什么 javac 在第二种情况下不会导致错误?
如果我的概念有误,请指导我。
根据 JLS 的 Section 5.2:
The compile-time narrowing of constant expressions means that code such as:
byte theAnswer = 42;
is allowed. Without the narrowing, the fact that the integer literal 42 has type int would mean that a cast to byte would be required:
byte theAnswer = (byte)42; // cast is permitted but not required
在JLS的Section 15.28中进一步定义了常量表达式。
由于表达式 5+6
是适合 byte
范围的常量表达式,它会在编译时自动变窄,无需显式转换。另一方面,由于表达式 c+6
不是常量表达式,它不会自动变窄,需要显式转换。
我写了程序
class First
{
public static void main(String[] args)
{
int c = 5;
byte b = c+6;
System.out.println(b);
}
}
我的 javac 输出是:
error: incompatible types: possible lossy conversion from int to byte
byte b = c+6;
^
1 error
但是如果我修改程序为:
class First
{
public static void main(String[] args)
{
byte b = 5+6;
System.out.println(b);
}
}
执行正常,输出:
11
我知道在操作之前,两个操作数都会转换为整数。然后 + 运算符产生一个整数。但是如果变量 c 是一个整数,那么常量 5 默认也是一个整数。为什么 javac 在第二种情况下不会导致错误?
如果我的概念有误,请指导我。
根据 JLS 的 Section 5.2:
The compile-time narrowing of constant expressions means that code such as:
byte theAnswer = 42; is allowed. Without the narrowing, the fact that the integer literal 42 has type int would mean that a cast to byte would be required:
byte theAnswer = (byte)42; // cast is permitted but not required
在JLS的Section 15.28中进一步定义了常量表达式。
由于表达式 5+6
是适合 byte
范围的常量表达式,它会在编译时自动变窄,无需显式转换。另一方面,由于表达式 c+6
不是常量表达式,它不会自动变窄,需要显式转换。