AI摘要
本文解析了Java中byte类型运算的常见面试题。指出byte、short、char在运算时会自动提升为int,需强制转换;解释了常量优化机制,即编译时直接计算字面量;并强调若常量运算结果超出目标类型范围,仍会报错。
下列代码是否存在错误,如果有,请指出说明,并且改正
1
pulbic static void main(String[] args){
byte b1 = 3;
byte b2 = 4;
byte b3 = b1 + b2;
}有错误,因为char,byte,short在计算时会自动类型提升为int
修改如下:
pulbic static void main(String[] args){
byte b1 = 3;
byte b2 = 4;
byte b3 = (byte)(b1 + b2);
}2
pulbic static void main(String[] args){
byte b3 = 3 + 4;
}没有错误,Java存在常量优化机制,在编译的时候javac就会将3和4这两个字面量进行运算,产生字节码byte b = 7
3
pulbic static void main(String[] args){
byte b3 = 300 + 4;
}有错误,虽然Java存在常量优化机制,但是最终计算结果超出了byte可接受长度范围,所以报错
评论 (0)