Sub topic 7
Evaluation Order and Side Effects
An expression is code that produces a value. An operator is a symbol that performs an action, and its operands are the values or expressions it uses.
Java evaluates operands from left to right. This matters when an expression has a side effect: a change that happens while Java works out a value. Printing text and changing a variable are side effects.
Grouping and order are different
Parentheses control grouping: they show which values belong together. They do not make Java evaluate the right side of an expression before the left side.
The following program makes the order visible. A method is a named block of code. Each call to mark prints a label, then returns its number.
Save this as EvaluationOrder.java:
public class EvaluationOrder {
static int mark(String label, int value) {
System.out.println(label);
return value;
}
public static void main(String[] args) {
int result = mark("left", 2)
+ (mark("middle", 3) * mark("right", 4));
System.out.println("result: " + result);
int count = 3;
int total = count++ + count;
System.out.println("total: " + total);
System.out.println("count: " + count);
}
}Compile and run it:
javac EvaluationOrder.java
java EvaluationOrderThe output is:
left
middle
right
result: 14
total: 7
count: 4Java calls mark for left first, even though the multiplication is grouped in parentheses. It then calls mark for middle and right, in that order. The parentheses group 3 * 4, so Java multiplies those values and then adds 2.
When an operand changes a variable
Now look at count++ + count. The count++ expression produces the current value of count, then increases the variable by one.
Java works from left to right:
- The left operand,
count++, produces3and changescountto4. - The right operand,
count, produces4. - Java adds
3 + 4, sototalbecomes7.
Afterward, count is still 4.
Expressions that both change and read a variable can be hard to follow. For clearer code, save the old value in a separate statement, increase the variable in another statement, and then add the values.
Practice
Exercise
If int x = 2; is followed by int y = x++ * 3 + x;, what are y and x afterward?
Show answer
y is 9 and x is 3. The left x++ produces 2 and changes x to 3. Java then calculates 2 * 3 + 3.