Sub topic 2
Grouping Expressions with Precedence and Parentheses
An expression is a combination of values and operations that produces a result. For example, 2 + 3 is an expression whose result is 5.
An operator is a symbol that performs an operation, such as + for addition. An operand is a value an operator acts on. In 2 + 3, the operands are 2 and 3.
What happens when an expression has more than one operator? Java uses rules to decide how to group the operands. Knowing these rules helps you predict the result and write expressions that other people can read.
Precedence: which operators group first
Operator precedence is the set of rules that determines how Java groups operators and their operands. Operators with higher precedence group before operators with lower precedence.
Consider this expression:
2 + 3 * 4
Multiplication has higher precedence than addition. So Java groups the expression as if it were written:
2 + (3 * 4)
The result is 14, not 20.
You can use parentheses to change the grouping:
(2 + 3) * 4
Now the addition is grouped first, and the result is 20.
The following table shows precedence for some common Java operators. Higher rows group before lower rows. This is not a complete list of Java operators.
| Precedence, high to low | Operators | Purpose | Column | Column |
|---|---|---|---|---|
| Higher | `*`, `/`, `%` | Multiplication, division, remainder | ||
| `+`, `-` | Addition, subtraction | |||
| `<`, `<=`, `>`, `>=` | Compare which number is smaller or larger | |||
| `==`, `!=` | Test whether values are equal or not equal | |||
| `&&` | Both conditions must be true | |||
| `\ | \ | ` | At least one condition must be true | |
| Lower | `=` | Assign a value to a variable |
A variable is a named place to store a value. The assignment operator, =, stores the value on its right in the variable on its left.
For example, in result = 2 + 3 * 4, Java groups the multiplication and addition before the assignment. The value assigned to result is 14.
Use parentheses to make groups clear
Parentheses tell Java to treat the expression inside them as a group. They can change a result, or they can make the usual grouping easier to see.
Compare these expressions:
10 - 4 * 2has the result2. Multiplication groups first:10 - (4 * 2).(10 - 4) * 2has the result12. The parentheses group the subtraction first.10 - (4 * 2)also has the result2. These parentheses make the usual grouping visible.
You can put one pair of parentheses inside another pair. This is called nesting. Work from the inner group outward when you read the expression:
(2 + 3) * (10 - (2 * 3))
- The inner expression
2 * 3produces6. - The expression
10 - 6produces4. - The other group,
2 + 3, produces5. - Finally,
5 * 4produces20.
Parentheses must be balanced: each opening ( needs a closing ). They must also surround a valid expression. If they do not, the compiler—the tool that checks and translates Java code—reports an error.
Associativity: operators at the same level
What if operators have the same precedence? Associativity is the rule that decides how operators at the same precedence level group.
Most of the operators in the table group from left to right. For example, - and + have the same precedence:
10 - 4 - 2
This groups as (10 - 4) - 2, giving 4. It does not group as 10 - (4 - 2), which would give 8.
Multiplication and division also have the same precedence. So 18 / 3 * 2 groups as (18 / 3) * 2, giving 12. If you want the multiplication grouped first, write 18 / (3 * 2), which gives 3.
Assignment is different. It groups from right to left. In a = b = 7, the group is a = (b = 7). The assignment to b produces the value 7, which is then assigned to a. Both variables end up holding 7.
Grouping comparisons and conditions
A Boolean value is either true or false. A comparison such as score > 5 produces a Boolean value. You can combine comparisons with logical operators, which work with Boolean values.
For example:
score > 5 && score < 10
The comparisons group before &&. The expression therefore means:
(score > 5) && (score < 10)
Both comparisons must be true for the whole expression to be true.
The && operator also has higher precedence than ||. Compare:
true || false && falsegroups astrue || (false && false), so it istrue.(true || false) && falseisfalsebecause the parentheses change the grouping.
A common mistake is to write 1 < 2 < 3 to test a range. Java groups the first comparison as 1 < 2, which produces true. It cannot then compare true with the number 3 using <. Write 1 < 2 && 2 < 3 instead.
Try a complete program
Save this program as Grouping.java:
public class Grouping {
public static void main(String[] args) {
System.out.println(2 + 3 * 4);
System.out.println((2 + 3) * 4);
System.out.println(10 - 4 - 2);
System.out.println(10 - (4 - 2));
System.out.println(true || false && false);
System.out.println((true || false) && false);
int a;
int b;
a = b = 7;
System.out.println(a);
System.out.println(b);
}
}Compile and run it from the folder containing the file:
javac Grouping.java
java GroupingThe output is:
14
20
4
8
true
false
7
7Try changing the parentheses, then compile and run the program again. Predict each result before you run it.
Grouping is not the whole evaluation order
Evaluation means finding the value of an expression. Precedence tells Java how to group an expression; it does not, by itself, say which operand Java visits first.
Java evaluates operands from left to right. In 2 + 3 * 4, the multiplication belongs in a group, but the left operand 2 is still evaluated before the operands 3 and 4. The multiplication result is then used in the addition.
Some operators can skip an operand altogether. You will explore those rules later. For now, use precedence to work out the grouping, and do not assume that a high-precedence operator means its operands are visited before everything to its left.
Practice
Try each question before looking at its answer.
Exercise
What is the result of 12 - 3 * 2? What is the result of (12 - 3) * 2?
Show answer
The results are 6 and 18. Multiplication groups first in the first expression; parentheses group subtraction first in the second.
Exercise
Add parentheses to 18 / 3 * 2 so that its result is 3.
Show answer
Write 18 / (3 * 2).
Exercise
What is the result of true || false && false? How can parentheses change its result?
Show answer
It is true because && groups first. Writing (true || false) && false changes the result to false.