Java数据类型转换short s=1;s=s+1;与short s=1;s+=1;为什么不同

时间:2021-03-27 17:53:10

在Java中这些数据类型由低级到高级分别为,(byte,short,char)--int--long--float--double。

1、隐式转换:低级变量可以直接转换为高级变量,比如:

byte b;int i=b;long l=b;float f=b;double d=b;

2、显示转换:从高级变量到低级变量,比如:

int i=99;byte b=(byte)i;char c=(char)i;float f=(float)i;

 

 

这就是为什么short s=1;s=s+1;与short s=1;s+=1;不同的原因了。s=s+1这句先执行s+1然后把结果赋给s,由于1为int类型,所以s+1的返回值是int,编译器自动进行了隐式类型转换,所以将一个int类型赋给short就会出错。而s+=1不同由于是+=操作符,在解析时候s+=1就等价于s = (short)(s+1)。