Evaluation by Rewriting

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   hear noise   go to next page

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