赋值运算符有哪些:
1、基本的赋值运算符:=
(把=
右边的数据赋值给左边,左边必须是变量)
int a = 3; //把3赋值给变量a
2、扩展的赋值运算符:+=
,-=
,*=
,/=
,%=
(+=
把左边和右边做加法,然后赋值给左边)
int a = 3;
a += 4;
System.out.println(a); //输出:7
3、赋值运算符的面试题:
short s = 3;
s = s + 4;
System.out.println(a); //报错:有可能损失精度
因为short在运行时会转换为int,然后将int赋值给short时,会运行出错。
short s = 3;
s += 4;
System.out.println(a); //输出:7
可以正常输出:因为s+=4;
底层会进行强制转换,s = (short)(s+4);
所以会正常输出。