Variables and Assignment Statements
Read this chapter, which covers variables and arithmetic operations and order precedence in Java.
22. Evaluation by Rewriting
Answer:
Expression 16 - 12 / 4 2 + 6 / 2 8 + 4*2 8+4 * 2 12/2 - 3 6/8 + 2 Value 13 5 16 16 3 2
The last result is correct. First 6/8
is done using integer division,
resulting in 0
. Then that 0
is added to 2
.
Evaluation by Rewriting
When evaluating an expression, it can be helpful to do it one step at a time and to rewrite the expression after each step. Look at:
16 - 12 / 4
Do the division first, since it has highest precedence. Next, rewrite the expression replacing the division with its value:
16 - 3
Now evaluate the resulting expression:
13
You can write the process like this:
16 - 12 / 4
------
16 - 3
---------
13
The dashed lines show what was done at each step.
Question 23:
What is the value of the following expression?
24 / 2 - 8