Careeroza
Operator Precedence
Which Runs First?
| Priority (high to low) | Operators |
|---|---|
| 1 | postfix x++ x-- |
| 2 | unary ++x --x + - !, casts |
| 3 | * / % |
| 4 | + - |
| 5 | < > <= >= |
| 6 | == != |
| 7 | && |
| 8 | || |
| 9 | ?: (ternary) |
| 10 | = += -= ... |
Example
Example
Operators with the same priority run left to right. Use brackets to make your intent clear.
public class Main {
public static void main(String[] args) {
System.out.println(2 + 3 * 4); // * first
System.out.println((2 + 3) * 4);
System.out.println(20 - 6 / 2 * 3); // 6/2=3, 3*3=9, 20-9
System.out.println(10 > 5 && 3 > 4 || true);
System.out.println(100 / 10 % 3);
}
}Output
14 20 11 true 1
Tip: When in doubt, add brackets. They cost nothing and make code easier to read.