Operator Precedence and Associativity
Operator precedence determines how terms are grouped in an expression. It affects the way an expression is evaluated. Some operators have higher precedence than others. For example, the multiplication operation has a higher precedence than the addition operator.
Example: x = 7 + 3 * 2;
Here, x is assigned 13 and not 20, because the * operator has higher precedence than +, so 3 * 2 is evaluated first, then added to 7.
In the following table, the operator with the highest precedence appears at the top, and the lowest appears at the bottom.
| Category | Operator | Associativity |
|---|---|---|
| Parentheses | () | Left to Right |
| Postfix | expression++ , expression-- | Left to Right |
| Unary | ++expression , --expression , +expression , -expression , ~ , ! | Right to Left |
| Multiplicative | * / % | Left to Right |
| Additive | + - | Left to Right |
| Shift | << , >> , >>> | Left to Right |
| Relational | < , > , <= , >= , instanceof | Left to Right |
| Equality | == , != | Left to Right |
| Bitwise AND | & | Left to Right |
| Bitwise XOR | ^ | Left to Right |
| Bitwise OR | | | Left to Right |
| Logical AND | && | Left to Right |
| Logical OR | || | Left to Right |
| Conditional | ?: | Right to Left |
| Assignment | = , += , -= , *= , /= , %= , ^= , |= , <<= , >>= , >>>= | Right to Left |
Source Code:
public class OperatorPrecedence {
public static void main(String[] args) {
// Example 1: Arithmetic and Assignment Operators
int a = 10, b = 5, c = 2;
int result = a + b * c; // Multiplication (*) has higher precedence than addition (+)
System.out.println("Result (a + b * c): " + result); // Output: 20
// Example 2: Parentheses Changing Precedence
result = (a + b) * c;
System.out.println("Result ((a + b) * c): " + result); // Output: 30
// Example 3: Relational and Logical Operators
boolean isTrue = (a > b) && (b > c); // Relational (>) executes first, then Logical AND (&&)
System.out.println("isTrue ((a > b) && (b > c)): " + isTrue); // Output: true
// Example 4: Bitwise vs Logical Operators
boolean logicTest = true || false && false; // AND (&&) executes before OR (||)
System.out.println("Logic Test (true || false && false): " + logicTest); // Output: true
// Example 5: Assignment Operators with Arithmetic
int x = 5;
x += 10 * 2; // Multiplication (*) happens before assignment (+=) x=x+10*2
System.out.println("x after (x += 10 * 2): " + x); // Output: 25
// Example 6: Ternary Operator Precedence
int y = 10;
int z = 20;
int min = (y < z) ? y : z; // Ternary operator has lower precedence than comparison
System.out.println("Minimum value using ternary: " + min); // Output: 10
}
}Result:
Watch the video:
Ebook: https://softkhpc.blogspot.com/2025/05/java-programming-ebooks.html

