强制类型转换:自动类型提升运算的逆运算。
1.需要使用强转符:()
2.注意点:强制类型转换,可能导致精度损失。
class VariableTest3 {
public static void main(String[] args) {
double d1 = 12.9;
//精度损失举例1
int i1 = (int)d1;//截断操作
System.out.println(i1);
//没有精度损失
long l1 = 123;
short s2 = (short)l1;
//精度损失举例2
int i2 = 128;
byte b = (byte)i2;
System.out.println(b);//-128
}
}
class VariableTest4 {
public static void main(String[] args) {
//1.编码情况1:
long l = 123213;
System.out.println(l);
//编译失败:过大的整数
//long l1 = 21332423235234123;
long l1 = 21332423235234123L;
//****************
//编译失败
//float f1 = 12.3;
float f1 = (float)12.3;
//2.编码情况2:
//整型常量,默认类型为int型
//浮点型常量,默认类型为double型
byte b = 12;
//byte b1 = b + 1;//编译失败
//float f1 = b + 12.3;//编译失败
}
}