← Back to Core Java Course | Chapter 3: Operators | Lesson 9 of 9

Java Operator Precedence

Arithmetic Precedence

Just like in standard math, Java evaluates * and / before + and - within the same expression, so 2 + 3 * 4 evaluates to 14, not 20 -- multiplication happens first regardless of left-to-right position.

Example: Arithmetic Precedence

java
public class Main {
	public static void main(String[] args) {
		System.out.println(2 + 3 * 4); // 14, not 20 - multiplication runs first
	}
}

Relational and Logical Precedence

Relational operators like > or < are evaluated before logical operators like && or ||, which is why a > 5 && b < 10 doesn't need extra parentheses around each comparison to work correctly.

Example: Relational and Logical Precedence

java
public class Main {
	public static void main(String[] args) {
		int a = 6, b = 5;
		System.out.println(a > 5 && b < 10); // comparisons evaluated before &&, no extra parens needed
	}
}

Left-to-Right Associativity

When two operators share identical precedence, like two additions in a row, Java resolves them left to right -- 10 - 3 - 2 evaluates as (10 - 3) - 2 = 5, not 10 - (3 - 2).

Example: Left-to-Right Associativity

java
public class Main {
	public static void main(String[] args) {
		System.out.println(10 - 3 - 2); // (10 - 3) - 2 = 5, evaluated left to right
	}
}

Assignment Precedence

Assignment operators are the rare exception that evaluate right to left, which is exactly what makes a = b = c = 0; work as intended -- c is assigned first, then that result assigns to b, then to a.

Example: Assignment Precedence

java
public class Main {
	public static void main(String[] args) {
		int a, b, c;
		a = b = c = 0; // right to left: c assigned first, then b, then a
		System.out.println(a + " " + b + " " + c);
	}
}

Modulo Operator Priority

% shares the exact same precedence tier as * and /, so in a mixed expression like 10 + 6 % 4, the modulo is computed before the addition, giving 10 + 2 = 12.

Example: Modulo Operator Priority

java
public class Main {
	public static void main(String[] args) {
		System.out.println(10 + 6 % 4); // % computed first (same tier as * and /): 10 + 2 = 12
	}
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.