隐式类型转换
从低级类型向高级类型转换,系统将会自动执行,程序员无需进行任何操作。这种类型的转换称为隐式类型转换。下列基本数据类型会涉及数据类型转换,不包括逻辑类型和字符类型。这些类型按精度从低到高排列顺序为:byte < short < int < long < fioat < double。
隐式类型转换也要遵循一定的规则,解决在什么情况下将那种类型的数据转换成另外一种类型的数据。
操作数1的数据类型 | 操作数2的数据类型 | 转换后的数据类型 |
byte、short、char | int | int |
byte、short、char、int | long | long |
byte、short、char、int、long | float | float |
byte、short、char、int、long、float | double | double |
实例:
public class Conver{ //创建类
public static void main (string[] args){
//定义byte型变量mybyte,并把byte型变量允许的最大值赋给mybyte
byte mybyte = 127;
int myint = 150; //定义int型变量myint
float myfloat = 452.12f; //定义float型变量myfloat
double mydouble = 45.46546; //定义double型变量mydouble
System.out.println("byte型与float型数据进行运算结果为:" + (mybyte + myfloat));
System.out.println(“byte型与int型数据进行运算结果为:” + (mybyte = myint));
System.out.println("byte型与char型数据进行运算结果为:" + (mybyte + mychar));
System.out.println("double型与byte型数据进行运算结果为:" + (mydouble + mychar));
}
}
显示类型转换:
当高精度的变量的值赋给低精度的变量时,必须使用显示类型转换运算(右称强制类型转换)。
语法:(类型名)要转换的值
示例:
int a = (int)45.23; //此时输出a的值为45
long y = (long)456.6f; //此时输出y的值为456
int b = (int)'d'; //此时输出b的值为100
当执行显示类型转换时可能会导致精度损失。只是boolean类型以外其他基本类型之间的转换,全部都能以显示类型转换的方法达到。