※--自动类型提升顺序
--小容量的数据类型可以赋值给大容量的数据类型
基本类型提升的顺序
byte-->short-->int-->long-->float-->double
int i = 0;
double d = i;
System.out.println(d);//Output result:0.0
char-->int-->long-->float-->double
16.33F+10//float
int f = 16.33F+10;//compile error:类型不兼容:float类型无法转换为int类型 小转大不通过
float f = 16.33F+10;//Output result:26.33 cause:16.33F是float类型,
//而10是整数类型是java默认的int类型,又因float比int容量大,故java自动提升类型。
16.33F+10.99//double
float f = 16.33F+10.99;//compile error:类型不兼容:double类型无法转换为float类型 小转大不通过
double d = 16.33F+10.99;Output result:27.31 cause:16.33F是float类型,
//而10.99是整数类型是java默认的double类型,又因double比float容量大,故java自动提升类型。
--强制类型转换
--大容量的数据类型赋值给小容量的数据类型会有类型兼容问题,不能直接赋值,除非通过强制类型转换
语法格式:
类型1 变量a = (类型1) 变量b
类型1 变量a = (类型1) (表达式)
/**
*
* @Author Lantzrung
* @Date 2022年7月16日下午4:44:42
*
**/
byte item1 = 2;//102
byte item2 = 3;//103
byte item3 = item1+item2;
//编译错误:不兼容的类型: 从int转换到byte可能会有损失 [原因:两数相加的和是大于127]
solution:byte item4 = (byte)(item1+item3)
System.out.println("item4="+item4);//结果:-51
//205-128-->77-->-127+77-->-50 因为0不用算故此 要向前移动一位 -50-1-->-51
//(int强转byte类型容量不足,溢出,故从byte类型的最小值取值开始)
byte b = 182;//编译错误: 不兼容的类型: 从int转换到byte可能会有损失
solution:byte b = (byte)182;结果:-74
//(int强转byte类型容量不足,溢出,故从byte类型的最小值取值开始)
byte b1 = 2;//程序能输出2
short s = 45182;//编译错误:不兼容的类型:从int转换到short可能会有损失
solution: short s1 = (short)45182;//结果:-20354 和上述同理
int i = 21000000000;//编译错误:过大的整数:21000000000 210亿 int最大的整数值为21亿左右
long l = 21000000000;//错误:过大的整数:21000000000
solution:long l1 = 21000000000L;//在过大数值中加上L的字母就可以把int类型数组提升为long类
//型数组
System.out.println(l1);//210000000000
int item1 = 67;
byte item2 = item1;//编译error:不兼容的类型:从int转换到byte可能会有损失
solution:byte item2 = (byte)item1;//67 强转
short item3 = item1;//编译error:不兼容的类型:从int转换到short可能会有损失
solution:short item3 = (short)item1;//67 强转