Java类型转换
类型转换
当把一种基本类型的数据赋值给另外一种基本数据类型的变量时,就会涉及到类型转换,类型转换仅局限于数值型类型内部
- 由于Java是强类型语言,所以进行有些运算的时候,需要用到类型转换
数据类型的优先级别的高低和所占内存字节数有关,所占字节数越多,优先级越高
优先级别由低到高的顺序排序:
byte—short—char—int—long—float—double
运算中,不同类型的数据先转化为同一类型,然后进行运算
- Java中的基本数据类型转换分为:
- 自动类型转换(隐式类型转换)
- 强制类型转换(显式类型转换)
数据类型转换
public class Demo04 {
public static void main(String[] args) {
int i = 128;
double b = i;
System.out.println(i);
System.out.println(b);
System.out.println("====================");
System.out.println((int)23.7);
System.out.println((int)-45.89f);
System.out.println("====================");
char c = 'a';
int d = c+1;
System.out.println(d);
System.out.println((char)d);
}
}
运行结果:
128
128.0
====================
23
-45
====================
98
b
Process finished with exit code 0
注意问题:在整数之间进行类型转换时,数值不发生改变;而将整数类型,特别是比较大的整数类型转换成小数类型时,由于存储方式不同,有可能存在数据精度的损失
数据转换溢出问题
public class Demo05 {
public static void main(String[] args) {
int money = 10_0000_0000;
int years = 20;
int total = money*years;
long total2 = money*years;
long total3 = money*((long)years);
System.out.println(total);
System.out.println(total2);
System.out.println(total3);
}
}
运行结果:
-1474836480
-1474836480
20000000000
Process finished with exit code 0