Many programmers believe that the statement “x += i” is simply a shorthand for “x = x + i”. This isn’t quite true. Both of these statements are assignment expressions. The second statement uses the simple assignment operator (=), whereas the first uses a compound assignment operator. The compound assignment operators are +=, -=, *=, /=, %= etc.
The Java language specification says that the compound assignment E1 op= E2 is equivalent to the simple assignment,
E1 = (T) ((E1) op (E2)), where T is the type of E1.
In other words, compound assignment expressions automatically cast the result of the computation they perform to the type of the variable on their left-hand side. If the type of the result is identical to the type of the variable, the cast has no effect. If, however, the type of the result is wider than that of the variable, the compound assignment operator performs a silent narrowing primitive conversion. Attempting to perform the equivalent simple assignment would generate a compilation error.
Consider the following examples-
You might expect the value of x to be 123456 after this statement executes, but it isn’t; it’s -7616. The int value 123456 is too big to fit in a short. The automatically generated cast. It silently removes the two high-order bytes of the int value.
prog.java:5: error: incompatible types: possible lossy conversion from int to short x = x + i; ^
It is clear from above examples that compound assignment expressions can cause undesirable results and should be used carefully for types like byte, short, or char. If we use them, we must ensure that the type of expression on right is not of higher precision.
This article is contributed by Shubham Juneja. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Compound assignment operators in Java
- What is the difference between = (Assignment) and == (Equal to) operators
- Difference between Simple and Complex View in SQL
- Interesting facts about Array assignment in Java
- Simple Calculator via UDP in Java
- Simple Calculator using TCP in Java
- Java Swing | Simple Calculator
- Java Swing | Create a simple text editor
- Difference between x++ and x=x+1 in Java
- Difference between while and do-while loop in C, C++, Java
- Difference between Groovy and Java
- Difference between for and do-while loop in C, C++, Java
- Difference between for and while loop in C, C++, Java
- Difference between super() and this() in java