Page 112 - Introduction to Programming with Java: A Problem Solving Approach
P. 112

                78
Chapter 3 Java Basics
What does the following expression evaluate to?
(c + a / b) / 10 * 5
Here’s the solution:
1. (c + a / b) / 10 * 5 ⇒
2. (3.0 + 5 / 2) / 10 * 5 ⇒ 3. (3.0 + 2) / 10 * 5 ⇒
4. 5.0 / 10 * 5⇒
5. 0.5 * 5 ⇒
6. 2.5
In solving expression evaluation problems, we recommend that you show each step of the evaluation process so your solution is easy to follow. In the above solution, we show each step, and we also show line numbers. There’s normally no need to show line numbers, but we do it here to help with our explanation. From line 1 to line 2, we replace variables with their values. From line 2 to line 3, we evaluate the highest priority operator, the / inside the parentheses. From line 3 to line 4, we evaluate the next highest priority operator, the + inside the parentheses. Study the remaining lines on your own.
Let’s do one more expression evaluation practice problem. Given these initializations:
int x = 5;
double y = 3.0;
What does the following expression evaluate to?
(0 % x) + y + (0 / x)
Here’s the solution:
t
i
i
e
en
nt
t
Apago PDF Enhancer
(0 % x) + y + (0 / x) ⇒
(0 % 5) + 3.0 + (0 / 5) ⇒ 0 + 3.0 + (0 / 5) ⇒
0 + 3.0 + 0 ⇒
3.0
Perhaps the trickiest part of the above solution is evaluating 0 % 5 and 0 / 5. They both evaluate to 0. This grade school arithmetic notation shows why:
0
5 􏰀0 -0 0
3.17 More Operators: Increment, Decrement, and Compound Assignment
So far, we’ve covered Java math operators that correspond to operations found in math books—addition, subtraction, multiplication, and division. Java provides additional math operators that have no counter- parts in math books. In this section, we’ll talk about the increment, decrement, and compound assignment operators.
    q
q
u
u
o
o
t
     r
r
e
e
m
m
a
a
i
in
n
d
de
e
r
r
  









































   110   111   112   113   114