public class Test {
pubilc static void main(String[] args) {
byte a = 5;
a = a + 5;//erro;
byte b = 5;
b += 5;//没问题
}}为什么是这样的情况。。???求。。运行机制。。
pubilc static void main(String[] args) {
byte a = 5;
a = a + 5;//erro;
byte b = 5;
b += 5;//没问题
}}为什么是这样的情况。。???求。。运行机制。。
a = a + 5;//erro;
是错的 ,因为 a+5是int类型 。 需要把 a+5强制转换为 byte 类型; byte b = 5;
b += 5;//没问题
运行的时候会存在一个隐式的类型转换,整个过程是相同的 也是按照 int计算的,不过,存在一个隐士的转换由虚拟机实现。 就相当于 byte b=5 ;
b=(byte)b+5;
还记得这个不,经典面试题:short s1 = 1; s1 = s1 + 1;有什么错? short s1 = 1; s1 += 1;有什么错?答:short s1 = 1; s1 = s1 + 1; (s1+1运算结果是int型,需要强制转换类型)
short s1 = 1; s1 += 1;(可以正确编译)
a += value;
<==>a = (type)(a+value);
byte a = 5;
a = a + 5;a+5后变为int行,需要变为:a=(byte)(a+5)
byte b = 5;
b += 5;//没问题