Sub topic 2
Grouping Expressions with Precedence and Parentheses
When Java calculates a value, it needs to know which operations belong together. The rules for grouping can change the result.
An expression is a combination of values and operations that produces a result. An operator is a symbol that tells Java what operation to perform, such as +. An operand is a value an operator works on. In 2 + 3, the operands are 2 and 3.
Precedence: which operations group first?
Precedence is the rule Java uses to decide how to group different operators. Multiplication has higher precedence than addition.
In 2 + 3 * 4, Java groups 3 * 4 together. The result is 2 + 12, or 14.
Parentheses can change the grouping. In (2 + 3) * 4, Java groups the addition first. The result is 5 * 4, or 20.
The table shows a few common arithmetic groups, from highest to lowest precedence.
| Group | Operators | Example |
|---|---|---|
| Parentheses | `( )` | `(2 + 3) * 4` |
| Unary signs | `+`, `-` before one value | `-3 * 2` |
| Multiplication, division, remainder | `*`, `/`, `%` | `3 * 4 + 2` |
| Addition and subtraction | `+`, `-` between values | `3 + 4 - 2` |
A unary operator works on one operand. For example, the unary minus in -3 makes the value negative. The remainder operator, %, finds the amount left after division.
This table is not a complete list of Java operators. When an expression is hard to read, use parentheses to make its grouping clear.
Associativity: operators at the same level
What happens when operators have the same precedence? Associativity is the rule that decides how they group.
Addition and subtraction group from left to right. So 8 - 3 - 1 groups as (8 - 3) - 1, which gives 4. If you want the other grouping, write 8 - (3 - 1), which gives 6.
Multiplication and division also group from left to right. In 12 / 3 * 2, Java groups the division first: (12 / 3) * 2 gives 8.
Not every operator groups left to right. Assignment uses = to store a value in a variable. It groups right to left: x = y = 6 means x = (y = 6). Both variables receive 6.
Try it in Java
Save this program as Main.java. Compile and run it as you would any simple Java program.
public class Main {
public static void main(String[] args) {
System.out.println(2 + 3 * 4); // 14
System.out.println((2 + 3) * 4); // 20
System.out.println(8 - 3 - 1); // 4
System.out.println(8 - (3 - 1)); // 6
System.out.println(12 / 3 * 2); // 8
}
}Check your understanding
Exercise
What does 10 - 2 * 3 produce? How can you change the grouping to produce 24?
Show answer
It produces 4, because multiplication groups first. Write (10 - 2) * 3 to produce 24.
Exercise
How does Java group 20 / 5 * 2, and what is the result?
Show answer
It groups from left to right: (20 / 5) * 2. The result is 8.