数据类型转换
数据类型转换分为隐式类型转换和显示类型转换
一、 隐式类型转换
- 从低精度数据类型向高精度数据类型转换
- 按精度从低到高排列顺序为:byte < short < int < float < double
- short < char < int
- 代码示例:
public static void main(String[] args) {
int x = 50;
float y = x;
System.out.println(y);
}
输出结果:
二、显示类型转换
- 从高精度数据类型向低精度数据类型转换
- 当执行显示类型转换时可能会导致精度损失。必须使用强制类型转换。
- 代码示例:
```java
public static void main(String[] args) {
int x = 50;
byte y = (byte) x;
System.out.println("y的结果为:" + y);
float f = 3543.3432f;
int f1 = (int) f;
System.out.println("f1的结果为:" + f1);
char c = 'A';
short i = (short) c;
System.out.println("i的结果为:" + i);
}
-
输出结果:
-
当把整数赋值给byte、short、int、long型变量时,不可以超出这些变量范围,否则必须使用强制类型转换。示例如下:
public static void main(String[] args) {
byte a = (byte)129;
System.out.println("a的结果为:" + a);
}