/*
- 基本数据类型之间的运算规则:
- 前提:这里讨论的只是7种基本数据类型变量间的运算(不包含boolean)
- 1.自动类型提升
- 结论:当容量小的数据类型的变量与容量大的数据类型的变量作运算时,结果自动提升为容量大的数据类型
byte、char、short --> int --> long --> float --> double - 特别:当byte、char、short三种类型的变量做运算时,结果为int类型
- 2.强制类型转换(逆过程):自动类型提升运算的逆运算。
- ①需要使用强转符:()
- ②注意点:强制类型转换,可能导致精度损失
- 说明:容量大小指的是表示数的范围的大小。比如:float容量大于long的容量
*/
public class VariableTest2 {
public static void main(String[] args) {
//一、自动类型提升
byte b1=2;
int i1=12;
//byte b2=b1+i1;//编译不通过(can't from int to byte)
int i2=b1+i1;
long l1=b1+i1;
System.out.println(i2);//可
System.out.println(l1);//可
float f1=b1+i1;;
System.out.println(f1);//可,自动补上一个小数-->“xx.0”
short s1=123;
double d1=s1;
System.out.println(d1);//123.0
//***********************************
char c1='a';//'a'为97
int i3=10;
int i4=c1+i3;
System.out.println(i4);
short s2=10;
//short s3=c1+s2;//编译不通过(cannot convert from int to short)
//char c2=c1+s2;//编译不通过(cannot convert from int to char)
byte b2=10;
//char c3=c1+b2;//编译不通过(cannot convert from int to char)
//short s3=b2+s2;//编译不通过(cannot convert from int to short)
//*********************************************************************
//二、强制类型转换(逆过程)
double d1=12.3;
//int i1=d1;//编译不通过(cannot convert from double to int)
//强转符(),括号中写转换的类型
int i1=(int)d1;//阶段操作
System.out.println(i1);
//精度损失举例(一)
d1=12.99;
System.out.println(i1);
//即不存在四舍五入的现象
//没有精度损失
long l1=123;
short s2=(short)l1;
System.out.println(s2);
//精度损失举例(二)
int i2=128;
byte b=(byte)i2;
System.out.println(b);//输出为-128
//转换的是字节里的编码,int中的“10000000”转换到byte中,最前面的一位变成“-”号。
}
}
输出:
14
14
14.0
123.0
107
12
12
123
-128

被折叠的 条评论
为什么被折叠?



