Understand the rules that dictate the order of operations in Java expressions, similar to PEMDAS or BODMAS in mathematics.
Java · beginner · 15 min · 15 steps · free
() to override the default order of operations.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);
}
}result1. The expression on the right will be evaluated first before the value is assigned.10 + 5 * 2, the multiplication operator * has higher precedence than the addition operator +. Therefore, 5 * 2 is evaluated first, resulting in 10.10 + 10, which evaluates to 20. This value is assigned to result1.result1 to the console.result2. Parentheses () have the highest precedence, so the expression inside them is evaluated first.(10 + 5) evaluates to 15. The main expression now becomes 15 * 2.15 * 2 is 30. This value is assigned to result2.result2.a, b, and c.a, b, and c.a, b, and c.a - b / c + 1, the division / has higher precedence than subtraction - and addition +. So, b / c (10 / 5) is evaluated first.20 - 2 + 1. Subtraction and addition have the same precedence, so they are evaluated from left to right. First, 20 - 2 is calculated.18 + 1, which results in 19. This final value is assigned to result3.result3.= has one of the lowest precedences.&&) and logical OR (||). && is higher.← Ternary Operator · Conditional Statements (if-else) →