Check Operator Precedence in Java
Problem
When an expression mixes several operator categories, Java doesn't evaluate left to right — arithmetic operators run before relational operators, which run before logical operators, regardless of where each appears in the expression.
Given an expression mixing arithmetic, relational, and logical operators, evaluate it step by step in the order Java actually applies, and print the final result.
Java Program
public class CheckOperatorPrecedence {
public static void main(String[] args) {
System.out.println("Expression: 10 + 2 * 5 > 15 && 4 < 6");
int step1 = 2 * 5; // * runs before +
System.out.println("Step 1 (* before +): 2 * 5 = " + step1);
int step2 = 10 + step1; // + runs before >
System.out.println("Step 2 (+ before >): 10 + " + step1 + " = " + step2);
boolean step3 = step2 > 15; // arithmetic finishes before relational runs
System.out.println("Step 3 (arithmetic before >): " + step2 + " > 15 = " + step3);
boolean step4 = 4 < 6;
System.out.println("Step 4 (< evaluated): 4 < 6 = " + step4);
boolean result = step3 && step4; // && runs last of all
System.out.println("Step 5 (&& evaluated last): " + step3 + " && " + step4 + " = " + result);
// The same expression written directly, confirming it matches the step-by-step result
boolean direct = 10 + 2 * 5 > 15 && 4 < 6;
System.out.println("Result: " + direct);
}
}Output
Core Logic
Breaking the mixed expression into the same steps Java's precedence rules would apply shows why the naive left-to-right reading would get a different, wrong order.
- 1Multiplication runs before addition, so
2 * 5is computed first, giving10— not10 + 2first, even though it appears first left to right. - 2With multiplication done, addition runs next:
10 + 10 = 20. - 3Arithmetic always finishes before relational operators run, so
20 > 15is evaluated only once the left-hand side is a plain number:true. - 4
4 < 6is evaluated on its own the same way, independent of the left-hand side:true. - 5Logical AND runs last of all, combining the two already-evaluated booleans:
true && true = true.
10 + 2 * 5 > 15 && 4 < 6 reduces step by step to 20 > 15 && 4 < 6, then true && true, then true.Key Point: Precedence, not left-to-right reading order, decides which operator runs first — * and / outrank + and -, arithmetic outranks relational (> < >= <=), and relational outranks logical (&& ||); parentheses can always override the default order explicitly.