How is the compound assignment operator + = computed ?, Value assignment operator
This article Reprinted from: http://tanlan.blog.51cto.com/3450625/1575936
Question:
short s1 = 1; s1 = s1 + 1;
What's wrong?
short s1 = 1; s1 +=1;
What's wrong?
At first glance, there seems to be no difference between the two codes, but their execution results are different.
The result is that the first code has an error and the second code has no error.
Analysis of the first code:
The second sentence of this Code (s1 = s1 + 1) is simply adding two numbers and assigning the result to the first variable.
The data type of the calculation result is determined by the following rules in sequence:
1. If the expression or number involved in the addition operation has the double type, the result is the double type.
2. If the expression or number involved in the addition operation has the float type, the result is of the float type.
3. If the expression or number involved in the addition operation has the long type, the result is the long type.
4. If the expression or number involved in the addition operation is not of the Data Type above 3, all results will be of the int type.
According to this rule, s1 = s1 + 1; then the final calculation result should be int, so an error occurs when s1 is assigned to the short type.
Analysis of the second code:
A composite value assignment expression similar to num1 + = num2 is actually equivalent to (num1 type) (num1 + num2 ), that is, the result of adding two numbers is forcibly converted to the Data Type of the left operand of the value assignment operator. The only difference is that num1 is calculated only once, so the theoretical compound assignment operator is more efficient.
S1 + = 1; it is equivalent to s1 = (short) (s1 + 1). Therefore, the result is correct.
Do you understand this rule? Please refer to the following two sections of code. Can you tell the correct answer?
What is the output value of the following code?
short x = 3;x += 4.6;System.out.print(x);
Is the following code incorrect?
int i = 5;long j = 8;i = i + j;i += j;