byte a = 11;
byte b = 2;
byte c = (byte)(a+b);
System.out.println(c);
short a = 11;
short b = 2;
short c = (short)(a+b);
System.out.println(c);
char a = 11;
char b = 2;
char c = (char)(a+b);
System.out.println(c);
结果: a + b 运算的结果皆为int类型,所以需要在加完之后添加类型转换为对于结果的类型.
分析:
1: 数据直接量可以直接赋值给byte,short,char,但是不能超出表示范围
2: byte,short,char,型数据在参与运算时的时候,先一律转换为int类型(这个特别注意)
注意: “=号后面的数据默认为int类型”.
byte a = 10;
byte b = 12;
byte c = (byte)a+(byte)b;
即使这样写也是错了,=号后面的数据默认为int类型,除非强转