1. Introduction of the problem
Cut to the chase, look at the following code, the results should be how
public class app{public static void Main (string[] args) { byte a=1; int B = Ten; A= a+b; System.out.println (a); a+=b; System.out.println (a); }}
What is the execution result of this code?
2. Implementation results
。。。。。。。。。。。。。。。。。。。 The answer is as follows .....
The compilation of the above code will be error, compile failed. Because in the third row inside the function, the left a is a byte type, the right of a is a byte type B is an int, and when a and B are added, type promotion occurs. The result of the a+b is an int, which naturally causes an error when assigning a value of type int to a byte type. But A+=b, this line of code can be executed normally, this is why?
3. Results analysis
The reason for the error on the third line has already been said, but A+=b, what is the reason for normal execution? according to the JLS (Java language Specification), the compound assignment operator expression E1 op= E2 is equivalent to E1 = (T) ((E1) op (E2)) where T is the type of E1, but E1 is only evaluated once. that is to say, the above a+b execution process is this, a = (byte) (a+b), at the time of the assignment of the cast, so it can be compiled through the normal. This explains the results of the compilation above.
Compound assignment operator for Java