一、隐式转换
1、把一个取值范围小的数值或者变量,赋值给另一个取值范围大的变量。
public class Demo {
public static void main(String[] args) {
int a = 100;
double b = a;
System.out.println(b);
}
}
输出结果:
100.0
2、运算过程中,取值范围小的数据,和取值范围大的数据进行运算,小的会先提升为大的之后,再进行运算。
public class Demo {
public static void main(String[] args) {
int a = 100;
double b = 10.1;
double c = a + b;
System.out.println(c);
}
}
输出结果:
110.1
3、byte short char三种数据在运算的时候,都会提升为int,然后再进行运算。
public class Demo {
public static void main(String[] args) {
byte a = 10;
byte b = 10;
//强制转换为byte
byte c = (byte)(a + b);
System.out.println(c);
//直接定义为int
int d = a + b;
System.out.println(d);
}
}
输出结果:
20
20
二、强制转换
把一个取值范围大的数值或变量,赋值给一个取值范围小的变量,需要加入强制转换。
public class Demo {
public static void main(String[] args) {
double a = 11.1;
int b = (int)a;
System.out.println(b);
}
}
输出结果:
11