Java Operator Precedence
Operator precedence is required when multiple operators are on the same line, your program needs to know which operation to evaluate first. In Java, the order is:
Order | Process |
---|---|
1 | () Operators within a pair of parentheses evaluated left to right |
2 | ++ or -- evaluated from right to left |
3 | * or / evaluated from left to right |
4 | + or - evaluated from left to right |
Let’s have a look at this in action by considering the following:
10 – 2 * 3 / 2 – 6 + 3
By applying the rules of precedence we should evaluate it in the following order:
Order | Calculation | Precedence Progression |
---|---|---|
1 | 2 * 3 = 6 | 10 – 2 * 3 / 2 – 6 + 3; |
2 | 6 / 2 = 3 | 10 – 6 / 2 – 6 + 3; |
3 | 10 - 3 = 7 | 10 – 3 – 6 + 3; |
4 | 7 – 6 = 1 | 7 – 6 + 3; |
5 | 1 + 3 = 4 | 1+ 3; |
6 | 4 |