Sub topic 7
Evaluation Order and Side Effects
When an expression has several parts, Java needs rules for deciding which part to evaluate first. This matters when evaluating one part changes a value or prints a message.
This chapter assumes you know Java variables and basic data types, and that you can write and run a simple Java program.
What evaluation changes
An expression is code that produces a value. To evaluate an expression means to work out that value. An operator, such as +, acts on values called operands.
A side effect is a change that happens while code runs, apart from producing a value. For example, code has a side effect when it:
- Changes a variable.
- Prints a message.
- Changes data stored elsewhere.
A method is a named block of code that runs when you call it. A method can return a value to the code that called it. It can also have side effects before it returns.
For example, n++ produces the current value of n and then increases n by one. The increase is a side effect. If another part of the expression uses n, the order matters.
Grouping is not evaluation order
Precedence tells Java how to group operators. Multiplication groups before addition. For example, 2 + 3 * 4 groups as 2 + (3 * 4).
Evaluation order is a different rule. For most operators, Java evaluates the left operand before the right operand. It evaluates each operand fully before moving to the next one.
This does not mean Java always performs the arithmetic from left to right. In 2 + 3 * 4, Java evaluates the left operand of + first. It then evaluates the right operand, 3 * 4. The multiplication produces 12, so the final addition is 2 + 12.
With plain numbers, the order may be hard to see. With methods that print messages, it becomes visible.
Trace a complete program
Save this program as EvaluationOrderDemo.java.
public class EvaluationOrderDemo {
static int count = 0;
static int mark(String label, int value) {
System.out.println(label);
return value;
}
static int next() {
count++;
System.out.println("next: " + count);
return count;
}
static void show(int first, int second) {
System.out.println("show: " + first + ", " + second);
}
public static void main(String[] args) {
int result = mark("left", 2)
+ mark("middle", 3) * mark("right", 4);
System.out.println("result: " + result);
show(next(), next());
System.out.println("count: " + count);
int n = 2;
int total = n++ + n++ * 2;
System.out.println("total: " + total);
System.out.println("n: " + n);
}
}Here, count is a variable shared by the methods in this class. The mark method prints a label and returns the number it receives. The next method increases count, prints it, and returns it. The show method prints the two numbers it receives.
Compile and run the program:
javac EvaluationOrderDemo.java
java EvaluationOrderDemoIts output is:
left
middle
right
result: 14
next: 1
next: 2
show: 1, 2
count: 2
total: 8
n: 4Follow the arithmetic expression
Look at the first expression:
mark("left", 2) + mark("middle", 3) * mark("right", 4)Multiplication groups before addition, so this is grouped as:
mark("left", 2) + (mark("middle", 3) * mark("right", 4))The parentheses show grouping. They do not make the middle and right calls run before the left call. Java evaluates the left operand of + first.
| Step | What happens | Value produced |
|---|---|---|
| 1 | `mark("left", 2)` prints `left` | `2` |
| 2 | `mark("middle", 3)` prints `middle` | `3` |
| 3 | `mark("right", 4)` prints `right` | `4` |
| 4 | Java multiplies the two values on the right | `12` |
| 5 | Java adds the left value to that result | `14` |
The printed labels reveal the order of the method calls. The result reveals how the arithmetic was grouped.
Follow the method arguments
An argument is a value supplied to a method call. In this call, the two calls to next() supply the arguments for show:
show(next(), next());Java evaluates method arguments from left to right before it runs the called method. Here is the sequence:
- The first
next()changescountfrom0to1, printsnext: 1, and returns1. - The second
next()changescountfrom1to2, printsnext: 2, and returns2. - The
showmethod runs withfirstequal to1andsecondequal to2.
That is why show: 1, 2 appears after both next messages. The final value of count is 2.
Follow changes to a variable
The last expression in the program is:
n++ + n++ * 2Before it runs, n is 2. Each n++ produces the old value of n, then increases n. The multiplication is grouped on the right, but Java still evaluates the left operand of + first.
| Step | What happens | Value of `n` afterward |
|---|---|---|
| 1 | The left `n++` produces `2` and increases `n` | `3` |
| 2 | The right `n++` produces `3` and increases `n` | `4` |
| 3 | Java multiplies `3` by `2` | `4` |
| 4 | Java adds `2` and `6` | `4` |
The value assigned to total is 8. The final value of n is 4.
This expression is valid, but it is not easy to read. Changing the same variable twice in one expression makes a reader trace every step.
Make the order clear
You can get the same result with separate statements. Save this program as ClearOrder.java and run it in the same way as the first program.
public class ClearOrder {
public static void main(String[] args) {
int n = 2;
int first = n;
n++;
int second = n;
n++;
int total = first + second * 2;
System.out.println("total: " + total);
System.out.println("n: " + n);
}
}This also prints total: 8 and n: 4. The calculation is longer, but each change to n is on its own line.
Be careful when assigning back to a variable that an expression also changes. If n starts at 3, then n = n++ first produces 3 and increases n to 4. The assignment then stores the produced value, 3, back into n. The final value is 3, not 4. Avoid writing code this way.
When evaluation stops early
If evaluating part of an expression fails, Java does not continue with the parts that come after it. A runtime error is a problem that occurs while the program is running. An exception is a signal Java uses to report such a problem.
Save this program as StopsEarly.java:
public class StopsEarly {
static int mark(String label, int value) {
System.out.println(label);
return value;
}
public static void main(String[] args) {
int zero = 0;
int total = mark("first", 1) + 10 / zero + mark("last", 2);
System.out.println(total);
}
}The first call prints first. Then integer division by zero causes an exception. The call that would print last is never reached, and total is not printed. Java reports the exception and stops this program because the program does not handle it.
This is another reason order matters: a side effect that happens before an error is not undone just because the rest of the expression fails.
Practice
Trace each expression before looking at its answer. Keep track of both the value produced and any variable changes.
Exercise
If n starts at 4, what are total and n after int total = n++ + n++ * 2;?
Show answer
The first increment produces 4, and the second produces 5. The total is 4 + 5 * 2, or 14. The final value of n is 6.
Exercise
In the demonstration program, why does mark("left", 2) print before mark("middle", 3), even though multiplication groups before addition?
Show answer
Grouping decides which values are multiplied. Evaluation order makes Java evaluate the left operand of addition before its right operand.
Exercise
If n starts at 7, what is its value after n = n++;?
Show answer
It is 7. The increment briefly changes n to 8, but the assignment stores the old value, 7, back into n.