当前位置:网站首页>short i =1; I=i+1 and short i=1; Difference of i+=1

short i =1; I=i+1 and short i=1; Difference of i+=1

2022-07-06 19:20:00 qq_ thirty-seven million seven hundred and five thousand five h

short i =1; i=i+1 And short i=1; i+=1 The difference between


It's typical to arrive JAVA Basic interview questions , I met in the last interview , Now take a note of .

short i =1; i=i+1;
short i=1;i+=1;
What's the difference between the two ?
When performing arithmetic operations on variables of two data types with different capacities ,java It will automatically improve the accuracy of small volume variables , And then we do the calculation , The result type obtained is the promoted large-capacity data type . If the result is assigned to a variable of small data type , You must perform forced type conversion , Otherwise, the compiler will report a loss of accuracy error . For example, the landlord , use i To express 1:
short s1 = 1;
int i = 1;
First , because short The type is 16 Bit , and int The type is 32 Bit , It's going on
(s1+i) Operation time , Automatically put s1 Upgrade to 32 position , Then with i Add up , And what you get is 32 Bit , And then
s1=s1+i; Must report wrong , Because if the assignment succeeds , Just lower 16 Bit is assigned to s1, Although this is exactly what the landlord wants , But the compiler cannot determine what your intention is .
Execute forced transfer :
s1=(short)(s1+i); That's fine .
s1+=i; It can compile and get correct results , and s1=s1+i; But report a mistake , Because they are not equivalent ,s1+=i The way java Would be right i Narrow conversion , Automatically executed by the compiler .

原网站

版权声明
本文为[qq_ thirty-seven million seven hundred and five thousand five h]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207061122494126.html