类型转换
类型转换分为强制转换和自动转换。
首先将数据类型从低容量到高容量排序如下:
低-- byte, short, char< int < long < float --高
(在这里float>long是因为小数具有优先级)
- 强制转换
当从高容量向低容量的数据类型进行转换时需要进行强制转换。(若直接写byte b=i;
将会报错)
int i= 128;
byte b=(byte)i; //强制转换
System.out.println(i);//output:128
System.out.println(b);//output:128
- 自动转换
当从低容量向高容量的数据类型转换时不需要任何操作。
byte b=69;
int i=b;
System.out.println(i);//output:69
System.out.println(b);//output:69
注意点
- 不能对布尔值转换
- 不能将对象类型转换为不相干的类型
- 在把高容量转换到低容量的时候,需要强制转换
- 转换的时候可能存在内存溢出,或精度问题
溢出问题
操作大数字时,需要注意溢出问题。
例子:
int salary=10_0000_0000;
//JDK7新的特性,数字之间可以用下划线分割,方便看懂大数字
int years=20;
int total=years*salary;
System.out.println(total);
//output: -1474836480
output: -1474836480
出现这种情况就是因为我们要得到的数超出了int数据类型的最大值。
如果改变total的数据类型变成int,仍然不能解决此问题。
int salary=10_0000_0000;
int years=20;
long total=salary*years;
System.out.println(total);
//output: -1474836480
output: -1474836480
结果不变是因为在给total赋值前salary*years已经计算完成了。
解决方法:
将salary或者years在进行运算之前强制类型转换成long。
int salary=10_0000_0000;
int years=20;
long total=salary*((long)years);
//或者 long total=((long)salary)*years;
System.out.println(total);
//output:20000000000
output:20000000000
salary和years转换一个即可。