In this lesson, you will learn.
1. Hierarchy: Some operators have higher precedence than others. For example, multiplication and division have higher precedence than addition and subtraction.
2. Associativity: If operators have the same precedence level, associativity rules determine the order. Most binary operators are left-associative, meaning they are evaluated from left to right.
3. Parentheses: Parentheses () can be used to override the default precedence order and group parts of an expression to be evaluated first.
public class PrecedenceExample {
public static void main(String[] args) {
// Multiplication (*) has higher precedence than addition (+)
int result = 10 + 2 * 5;
System.out.println(result); // Output: 20 (not 60)
}
}
public class MixedOperators {
public static void main(String[] args) {
int result = 4 + 2 * 10 / 5 - 3;
// * and / have higher precedence, evaluated left to right,
// then + and -
System.out.println(result); // Output: 5
}
}
public class OverridePrecedence {
public static void main(String[] args) {
int result = (4 + 2) * (10 / (5 - 3));
// Parentheses change the order of evaluation
System.out.println(result); // Output: 18
}
}
<pre class="wp-block-syntaxhighlighter-code">public class LogicalPrecedence {
public static void main(String[] args) {
boolean result = true || false && false;
// && has higher precedence than ||
System.out.println(result); // Output: true
}
}<br>
</pre>
public class UnaryBinaryPrecedence {
public static void main(String[] args) {
int a = 5;
int result = ++a + a++;
/* Prefix increment (++a) has higher precedence than
postfix increment (a++) */
System.out.println(result); // Output: 12 (6 + 6, then a becomes 7)
}
}
Below is a summary table of operator precedence in Java, from highest to lowest, along with small examples for each category of operators.
| Precedence | Operator Type | Operators | Example Expression | Result |
|---|---|---|---|---|
| Highest | Postfix | expr++, expr-- |
int a = 10; a++; |
10 (then a becomes 11) |
| Unary | ++expr, --expr, +expr, -expr, ~, ! |
int a = 10; -a; |
-10 |
|
| Multiplicative | *, /, % |
2 * 3 |
6 |
|
| Additive | +, - |
10 - 3 |
7 |
|
| Shift | <<, >>, >>> |
32 >> 2 |
8 |
|
| Relational | <, >, <=, >=, instanceof |
5 < 3 |
false |
|
| Equality | ==, != |
5 == 5 |
true |
|
| Bitwise AND | & |
5 & 3 |
1 |
|
| Bitwise exclusive OR | ^ |
5 ^ 3 |
6 |
|
| Bitwise inclusive OR | ` | ` | `5 | |
| Logical AND | && |
true && false |
false |
|
| Logical OR | ` | ` | ||
| Ternary | ? : |
true ? 1 : 2 |
1 |
|
| Assignment | =, +=, -=, *=, /=, %=, &=, ` |
=, ^=, <<=, >>=, >>>=` |
int a; a = 5; |
|
| Lowest | Comma | , |
int a = 1, b = 2; |
a=1, b=2 |
() can be used to override these rules and group parts of expressions to be evaluated in the order you desire.
There are no reviews yet. Be the first one to write one.
You must be logged in to submit a review.