java中使用二元操作符进行运算是会进行自动类型提升。
具体为:
如果两个操作数其中有一个是double类型,另一个操作就会转换为double类型。
否则,如果其中一个操作数是float类型,另一个将会转换为float类型。
否则,如果其中一个操作数是long类型,另一个会转换为long类型。
否则,两个操作数都转换为int类型。
看例子:
byte a = 5;
byte b = 4;
int c = a+b;//自动类型提升
a+=b;//自加没有自动类型提升问题
char char1 = 4;
char char2 = 4;
char cadd = (char) (char1 + char2);//自动类型提升
char1 += char2;//自加没有自动类型提升问题
short s = 4;
short t = 5;
int con = (s + t) ;//自动类型提升
s += t;//自加没有自动类型提升问题
byte bt = 1;
char ch = 5;
short sh = 5;
int i = 6;
long l =5l;
float f = 6.6f;
double j = 5.7;
long add = l + i ; //long + int 结果为long型
long add2 = l + sh ;//long + short 结果为long型
float add3 = l + f; //long + float 结果为float型
double add4 = l + j;//long + double 结果为double型
float add5 = i + f; //int + float 结果为float型
double add6 = i + j;//int + double 结果为double型
int add7 = i + ch;
int add8 = i + sh;
int add9 = i + bt;//int +(byte,short,char) 结果为int型
但是有一点要注意,final修饰的byte, short, char变量相加后不会被自动提升。
final char fch = 5;
final char fch1 = 6;
char fch2 = fch + fch1;//类型没有提升
No comments:
Post a Comment