< previous page page_48 next page >

Page 48
Another year passes
I am      40 years old
You are   41 years old
Let's print it again
I am      41 years old
You are   41 years old
Analysis: On lines 7 and 8 two integer variables are declared, and each is initialized with the value 39. Their value is printed on lines 9 and 10.
On line 11 myAge is incremented using the postfix increment operator, and on line 12 yourAge is incremented using the prefix increment operator. The results are printed on lines 14 and 15, and they are identical (both 40).
On line 17, myAge is incremented as part of the printing statement, using the postfix increment operator. Because it is postfix, the increment happens after the print, and so the value 40 is printed again. In contrast, on line 18 yourAge is incremented using the prefix increment operator. Thus, it is incremented before being printed, and the value displays as 41.
Finally, on lines 20 and 21 the values are printed again. Because the increment statement has completed, the value in myAge is now 41, as is the value in yourAge.
Precedence
In the complex statement
x = 5 + 3 * 8;
which is performed first, the addition or the multiplication? If the addition is performed first, the answer is 8 * 8, or 64. If the multiplication is performed first, the answer is 5 + 24, or 29.
New Term: Every operator has a precedence value, and the complete list is shown in Appendix A, Operator Precedence. Multiplication has higher precedence than addition, and thus the value of the expression is 29.
When two mathematical operators have the same precedence, they are performed in left-to-right order. Thus
x = 5 + 3 + 8 * 9 + 6 * 4;
is evaluated multiplication first, left to right. Thus, 8*9 = 72, and 6*4 = 24. Now the expression is essentially
x = 5 + 3 + 72 + 24;

 
< previous page page_48 next page >

If you like this book, buy it!