CHAPTER 4 ■ OPERATORS
Assignment Operators
The assignment operators set values and assign object references. The basic assignment operator (=) is
by far the most often used operator. Every time we put something like int = 0 (assigning a value to a
primitive) or Date now = new Date() (assigning an object reference to a variable) into an example, we
use the basic assignment operator.
Java provides a number of compound assignment operators (often called shortcut operators).
Listing 4-25 is an example of one of the compound assignment operators.
Listing 4-25. Compound assignment operator
int myInt = 2;
myInt *= 2; // equivalent to myInt = myInt * 2;
System.out.println(myInt); // prints 4;
Each of the compound operators applies the first operator within the compound operator and the
value after the compound operator and then applies the assignment operator. In the previous example,
the multiplication operator is applied to myInt with the value after the compound operator (in this case,
doubling the value of myInt) and then sets myInt to the result.
The compound assignment operators can lead to unexpected results. Consider the following code
snippet in Listing 4-26. Before reading past the snippet, ask yourself “What is the value of myInt at the
end?”
Listing 4-26. Compound assignment problem
int myInt = 2;
myInt *= (myInt = 4);
System.out.println(myInt);
The last assignment before the print statement is myInt = 4, so you might think the answer must be
- But we set myInt to 4 and then multiply it by itself, so you might think the answer must be 16. In fact,
neither is correct. The code snippet prints 8. It might seem odd at first, but it makes sense once you
understand how the JVM deals with a compound operator. When the JVM encounters the compound
operator, it knows myInt equals 2. Until the entire operator is resolved, the value of myInt can't be
changed. (This is the only case we know of where parentheses aren't processed first, by the way.)
Consequently, the assignment within the line is ignored, but the value within the assignment is used.
After all that, the result is 2 times 4, or 8.
■ Note This issue is pretty much an academic curiosity. It's an issue the developers of the Java language had to
account for, but smart programmers don't write code like this. Smart programmers break up their operations so
that the effect of each line is clear with minimal interpretation. Remember, if you program for a living, other
programmers have to read your code and understand it, and very few development shops will tolerate this kind of
confused and confusing code.
Table 4.3 shows all the assignment operators, including the compound operators.