We covered most of the functionality of the assignment operator, “=”, in our chapter on Literals and Variable assignments. To summarize:
• When assigning a value to a primitive, size matters. Be sure you know when implicit casting will occur, when explicit casting is necessary, and when truncation might occur.
• Remember that a reference variable isn’t an object; it’s a way to get to an object. (We know all you C++ programmers are just dying for us to say “it’s a pointer”, but we’re not going to.)
• When assigning a value to a reference variable, type matters. Remember the rules for supertypes, subtypes, and arrays.
Topics like bit shifting operators, bitwise operators, two’s complement and divide by zero are not part of the SCJP 5 exam. I am not saying these are not important topics in Java. Actually they are very important but from the SCJP exam perspective they are not part of the syllabus, so don’t waste time reading them.
Compound Assignment Operators
There are actually 11 or so compound assignment operators, but only the four most commonly used (+=, -=, *=, and /=), are on the exam. The compound assignment operators let lazy programmers shave a few keystrokes off their workload. Here are several example assignments, first without using a compound operator,
y = y - 6;
x = x + 2 * 5;
Now, with compound operators:
y -= 6;
x += 2 * 5;
The last two assignments give the same result as the first two.
Earlier versions of the exam put big emphasis on operator precedence (like: What’s the result of: x = y++ + ++x/z;). Other than a very basic knowledge of precedence (such as: * and / are higher precedence than + and -), you won’t need to study operator precedence, except that when using a compound operator, the expression on the right side of the = will always be evaluated first. For example, you might expect
x *= 2 + 5;
to be evaluated like this:
x = (x * 2) + 5; // incorrect precedence
since multiplication has higher precedence than addition. But instead, the expression on the right is always placed inside parentheses. it is evaluated like this:
x = x * (2 + 5);
Previous Chapter: Self Test - Chapters 15 to 21
Next Chapter: Chapter 23 - Relational Operators