Java基础之数据类型转换
boolean
- boolean不可以转换为其他的数据类型
隐式自动类型转换
隐式自动类型转换
(byte,short,char) < int < long < float < double
byte ---》 short,int,long,float,double short ---》 int,long,float,double char ---》 int, long,float,double int ---》 long,float,double long ---》 float,double float ---》 double
- byte能自动转为short,除此,byte,short,char不能自动相互转换
- 有多种数据类型混合计算的时候,系统首先自动转换为容量最大的那个类型再来继续计算
强制类型转换
- 容量大的类型在转换为小的类型的时候,必须加上强制转换符,此时可能造成精度降低或者溢出问题
- 当转换为精度和范围较小的类型时,可能会丢失数据。
byte数据类型范围为-128~127int i1 = 128; byte b = (byte)i1; int i2 = b; System.out.println("转换前:" + i1); System.out.println("转换后:" + i2); /* 转换前:128 转换后:-128 /*
提升原则
在算术运算和位运算中,数值类型的数据按以下原则进行类型提升
算术运算和位运算byte、short和char型自动转成int型,如:
byte b1=3;
byte b2=5;
byte c=b1+b2; //错误,运算时b1和b2已转换为int
int d=b1+b2; //正确
byte b=10;
short s=9;
char c ='c';
short r1=b+s; //错误
int r2= (b==10)?b:s; //正确
short r3= (b==10)?b:s; //正确
byte r4= (b==10)?b:s; //错误
- 在其他情况的运算中,运算的对象会自动转换为精度和范围高的类型