类型转换
Java属于强类型语言,进行某些运算时,需要用到类型转换
- 低 -------------------------------------------------------------> 高
- byte , short , char -> int -> long -> float -> double
运算中,不同类型的数据先转化位同一类型,然后进行运算
小数的优先级一定大于整数
强制类型转换
(类型)变量名 由高到低
int i = 128;
byte b = (byte)i; //强制转换
System.out.println(i); //128
System.out.println(b); //-128 内存溢出
char c = 'a';
int i1 = c+1;
System.out.println(i1); //98
System.out.println((char)i1);//b 强制转换
内存溢出问题
在操作比较大的数的时候,注意溢出问题
int money = 10_0000_0000;//JDK7新特性,数字之间可以用下滑线分割,且下划线不会被输出
int years = 20;
int total1 = money*years; //-1474836480,溢出
long total2 = money*years; //-1474836480,默认是int,转换之前就存在溢出问题
long total3 = money*((long)years);//200000000,先把一个数转为long
自动类型转换
由低到高
int i = 128;
double d = i; //自动转换
System.out.println(i); //128
System.out.println(d); //128.0
注意点
- 不能对布尔值进行转换
- 不能把对象类型转换位不相干的类型
- 在把高容量转换到低容量的时候,强制转换
- 转换的时候可能存在内存溢出,或者精度的问题
- 整数 long 类型和浮点数 float 类型数字后的字母尽量大写
System.out.println((byte)128); //-128 内存溢出
System.out.println((int)23.7); //23 精度问题