IntTest06.java
/*
结论:byte、char、short做混合运算的时候,各自先转换成int再做运算。
*/
public class IntTest06{
public static void main(String[] args){
char c1 = 'a';
byte b = 1;
// 注意:这里的“+”是负责求和的
System.out.println(c1 + b); // 98
// 错误: 不兼容的类型: 从int转换到short可能会有损失
// short s = c1 + b; // 编译器不知道这个加法最后的结果是多少。只知道是int类型。
// 这样修改行吗?
// 错误: 不兼容的类型: 从int转换到short可能会有损失
// short s = (short)c1 + b;
short s = (short)(c1+b);
short k = 98;
}
}
IntTest07.java
/*
结论:多种数据类型做混合运算的时候,最终的结果是“最大容量”对应的类型。
char+short+byte 这个除外。
因为char+short+byte混合运算的时候,会各自先转换成int类型进行运算。
*/
public class IntTest07{
public static void main(String[] args){
long a = 10L;
char c = 'a';
short s = 100;
int i = 30;
// 求和
System.out.println(a + c + s + i); // 237
// 错误:不兼容类型:从long转换到int可能会有损失
// 计算结果是long类型
int x = (int)(a + c + s + i);
System.out.println(x);
// 以下程序执行结果是:
// int类型的数据相除,最终得出的依然是int类型数据。
int temp = 10 / 3; // / 是除号。(最终取整)
System.out.println(temp); // 3
// 在java中计算结果不一定是精确的。
int temp2 = 1 / 2;
System.out.println(temp2); // 0
}
}