Core Java Fundamentals ยท Operators

Operator Precedence

Understand the rules that dictate the order of operations in Java expressions, similar to PEMDAS or BODMAS in mathematics.

PrecedenceDemo.java

public class PrecedenceDemo {
    public static void main(String[] args) {
        // Example 1: Default precedence (* has higher precedence than +)
        int result1 = 10 + 5 * 2; 
        System.out.println("Result 1 (10 + 5 * 2): " + result1);

        // Example 2: Using parentheses to override precedence
        int result2 = (10 + 5) * 2;
        System.out.println("Result 2 ((10 + 5) * 2): " + result2);

        // Example 3: Multiple operators with same precedence
        int a = 20;
        int b = 10;
        int c = 5;
        int result3 = a - b / c + 1; // Division -> Subtraction -> Addition
        System.out.println("Result 3 (20 - 10 / 5 + 1): " + result3);
    }
}

Step by step

  1. We declare an integer variable result1. The expression on the right will be evaluated first before the value is assigned.
  2. In the expression 10 + 5 * 2, the multiplication operator * has higher precedence than the addition operator +. Therefore, 5 * 2 is evaluated first, resulting in 10.
  3. Now the expression becomes 10 + 10, which evaluates to 20. This value is assigned to result1.
  4. The program prints the value of result1 to the console.
  5. Next, we declare result2. Parentheses () have the highest precedence, so the expression inside them is evaluated first.
  6. The expression (10 + 5) evaluates to 15. The main expression now becomes 15 * 2.
  7. 15 * 2 is 30. This value is assigned to result2.
  8. The program prints the value of result2.
  9. We declare and initialize three integer variables: a, b, and c.
  10. We declare and initialize three integer variables: a, b, and c.
  11. We declare and initialize three integer variables: a, b, and c.
  12. In the expression a - b / c + 1, the division / has higher precedence than subtraction - and addition +. So, b / c (10 / 5) is evaluated first.
  13. The expression becomes 20 - 2 + 1. Subtraction and addition have the same precedence, so they are evaluated from left to right. First, 20 - 2 is calculated.
  14. The expression is now 18 + 1, which results in 19. This final value is assigned to result3.
  15. Finally, the program prints the value of result3.