/*
前提:这里讨论只是7种基本数据类型变量间的运算。不包含Boolean类型的。
1.自动类型提升
结论:当容量小的数据类型的变量与容量大的数据类型的变量做运算时结果自动提升为容量大的数据类型。
byte、char、 short → int → long → float→ double
特别:当byte、char、short三种类型的变量做运算时,结果为int型。
2.强制类型转换:见test1
①.需要使用强转符:()
②.注意点:强转类型转换,可能导致精度损失。
说明:此时的容量大小指的是,表示数的范围的大和小。比如:float容量要大于long的容量
*/
class test{
public static void main(String[] args) {
byte b1=2;
int i1=129;
//编译不通过
//byte b2 =b1+i1;
int i2 =b1+i1;
long l1=b1+i1;
System.out.println(i2);
float f=b1+i1;
System.out.println(f);
short s1=123;
double d1=s1;
System.out.println(d1);//123.0
//特别的********
char c1 ='a';//97
int i3 =10;
int i4 = c1+i3;
System.out.println(i4);
short s2 =10;
//char s3=c1+s2;//编译不通过
byte b2=10;
//char c3=c1+b2;//编译不通过
//short s3=b2+s2;//编译不通过
//short s4 =b1+b2;//编译不通过
}
/*
强制类型转换:
①.需要使用强转符:()
②.注意点:强转类型转换,可能导致精度损失。
*/
class test2{
public static void main(String[] args) {
double d1=12.3;
//精度损失举例1
int i1=(int)d1;//截断操作
System.out.println(i1);
//没有精度损失
long l1 =123;
short s2=(short)l1;
//精度损失举例2
int i2=128;
byte b=(byte)i2;
System.out.println(b);//-128
}
class test2{
public static void main(String[] args) {
//1.编码情况:
long l =123456;
System.out.println(l);
//编译失败:过大的整数
//long l1 =123456487897899787;
long l1 =12345648789789787L;
//****************
//编译失败
//float f1 =12.3;
//2.编码情况2:
//整型常量,默认为int型
//浮点型常量,默认类型为double型
byte b=12;
//byte b1 =b+1;//编译失败
//float f1=b+12.3;//编译失败
}