Java Operator Precedence
In this page:
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
public class Main {
public static void main(String[] args) {
System.out.println(2 + 3 * 4); // 14, not 20 - multiplication runs first
}
}
Login to try C/C++/Java/PHP code in the editor
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
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
}
}
Login to try C/C++/Java/PHP code in the editor
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
public class Main {
public static void main(String[] args) {
System.out.println(10 - 3 - 2); // (10 - 3) - 2 = 5, evaluated left to right
}
}
Login to try C/C++/Java/PHP code in the editor
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
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);
}
}
Login to try C/C++/Java/PHP code in the editor
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
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 try C/C++/Java/PHP code in the editor
- Assuming
&&and||have equal priority, when&&runs first, soa || b && cisa || (b && c). - Expecting
-to be evaluated right to left, when10 - 4 - 3is3because it goes left to right. - Not using parentheses in complex expressions.
- Java has arithmetic, relational, logical, bitwise, and assignment operators for working with values.
- Increment, decrement, and the ternary operator offer short ways to update values or choose a result.
- Operator precedence determines how a mixed expression is evaluated.
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: