Page 480 - Introduction to Programming with Java: A Problem Solving Approach
P. 480
446 Chapter 11 Type Details and Alternate Coding Mechanisms
As you might have guessed, in executing this statement, the JVM first decrements a. This should make sense when you look at Appendix 2’s operator precedence table and confirm that the decrement operator has very high precedence. The JVM also executes b’s decrement operator early on, but its execution consists of using b’s original value and incrementing b afterwards. The operator precedence table shows that the + operator has higher precedence than the = operator, so the JVM next adds b’s original value to a’s decre- mented value. Finally, the JVM assigns the sum to c.
For many people, line 5 is particularly confusing. We showed you this example because you might see this kind of thing in someone else’s code, but if you want your code to be understandable, we recommend that you not do this yourself. That is, don’t embed ++ or -- expressions within other expressions. Instead of trying to do everything line 5 does in one statement, it would be more understandable to partition line 5 into three separate statements, like this:
5a a--;
5b c = b + a;
5c b--;
The JVM performs the evaluation in separate steps anyway, so writing it out does not incur any performance penalty. It takes more space on the page, but most people will agree that it’s easier to read.
When writing code, how do you decide which mode to use, prefix or postfix? It depends on the rest of your code. Usually, to minimize confusion, you’ll put increment and decrement operations on separate lines. Then it doesn’t matter which mode you use, but postfix is more common.
ment statements material in Chapter 3, Section 3.11 and the while loop material in Chapter 4, Section 4.8. Embedding an Assignment within Another Assignment
Assignments are sometimes embedded as expressions in larger statements. When that happens, remember that (1) an assignment expression evaluates to the assigned value, and (2) assignment operators exhibit right- to-left associativity. To see these concepts in action, consider this code fragment:
Apago PDF Enhancer
11.6 Embedded Assignments
This section supplements material you learned in Chapters 3 and 4. Specifically, it supplements the assign-
1
int a, b = 8, c = 5;
a = b = c;
s
2
3
4 System.out.println(a + " " + b + " " + c);
Line 3 shows an assignment expression embedded inside a larger assignment statement. Which of the two assignment operators does the JVM execute first? Since assignment operators exhibit right-to-left associa- tivity, the JVM executes the right assignment operation first. What does the b = c expression evaluate to?Itevaluatesto5becausetheassignedvalue,c,is5.Inevaluatingline3,replacetheb = cpartofthe statement with 5 to reduce the statement to:
a = 5.
Here’s what the code fragment’s trace looks like:
s
a
a
m
m
e
ea
a
s
s:
:
a
a
=
=(
(b
b=
=
c
c)
);
;