The compound assignment operators are: + =,-=, *=,/=,%=, <<=, >>=, >>>=, &=, ^=, and | =
The simple assignment operator is =;
The code is as follows:
public class Example009 {public static void main (string[] args) {short x = 1;int X1 = 1;int i = 123456;x + = i;//assignment 1x1 + = i;//Assignment 2system.out.println ("x =" + x + ", x1 =" + x1);}}
Output Result:
x = -7615,x1 = 123457
Results Analysis:
The code above uses an assignment operator that conforms to the value. The Java language specification mentions that compound assignment E1 op= E2 is equivalent to a simple assignment E1 = (t) ((E1) op (E2)), where T is the type of E1 unless E1 is computed only once. In other words, compound assignment expressions automatically transform the results of the calculations they perform to the type of their left variable. If the type of the result is the same as the type of the variable, then this transition has no effect. However, if the type of the result is wider than the type of the variable, then the compound assignment operator silently performs a narrowing of the original type conversion.
In the above code, the result of the assignment of 1 is the value of the Int,int type 123457 for the left operand type short is too large, the auto-generated transformation quietly to the int value of the high two bits to intercept, the remaining low 16-bit result is 7615.
Again, the following code:
Common class Example010 {public static void main (string[] args) {Object A = "Welcome attention to the citizen"; object a1 = "Welcome to the public"; String B = "Ape_it"; a + = B; Assignment 3 This can be compiled correctly on jdk1.7, previous version not tested a1 = A1 + B; System.out.println ("a=" + A + ", al=" + A1);}}
Output Result:
A= Welcome to the public number ape_it,al= Welcome to the public number Ape_it
The result here is the same as you think, but not the same as the original book (corresponding to the original book Puzzle 10:82). The blogger test was carried out on the jdk1.7, and the original book was carried out on the jdk1.5. The issue of assignment 3, which is not correctly compiled, has been resolved.
This article from "Winger" blog, declined reprint!
"Java doubts" compound assignment and simple assignment