0% completed
Operator precedence in Java determines the order in which operators are evaluated in an expression without explicit parentheses. Understanding these rules is essential for writing expressions that behave as expected.
When Java evaluates an expression, it follows a specific hierarchy: operators with higher precedence are evaluated before those with lower precedence. If operators have the same precedence, then the associativity (left-to-right or right-to-left) determines the order of evaluation.
For example, in the expression:
2 + 3 * 4
Multiplication (*
) has a higher precedence than addition (+
), so 3 * 4
is evaluated first, resulting in 2 + 12 = 14
.
Below is a table summarizing the precedence of several common operators in Java, from highest (evaluated first) to lowest (evaluated last):
Precedence Level | Operators | Associativity |
---|---|---|
Highest | () (parentheses) | - |
++ (postfix), -- (postfix) | Left-to-right | |
++ (prefix), -- (prefix), + (unary plus), - (unary minus), ! (logical NOT), ~ (bitwise NOT) | Right-to-left | |
* , / , % | Left-to-right | |
+ , - (binary addition and subtraction) | Left-to-right | |
<< , >> , >>> | Left-to-right | |
< , <= , > , >= | Left-to-right | |
== , != | 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 | |
Lowest | ?: (ternary conditional) | Right-to-left |
= (assignment), += , -= , *= , /= , %= etc. | Right-to-left |
Below is an example that demonstrates the precedence of multiplication and addition in an expression.
Explanation:
*
) is evaluated first, making 3 * 4
equal to 12
.+
) is then applied, yielding 2 + 12 = 14
.Below is an example that uses parentheses to change the natural order of operations.
Explanation:
2 + 3
) to be evaluated first, resulting in 5
.5 * 4 = 20
.Below is an example that demonstrates how arithmetic operators are evaluated before relational operators.
Explanation:
3 + 4
) is evaluated before the relational operator (>
).7
, which is compared to 6
, so the expression evaluates to true
.Below is an example that shows the precedence between logical AND (&&
) and logical OR (||
).
Explanation:
&&
) operation (false && false
) is evaluated first, resulting in false
.||
) operation then evaluates true || false
, which results in true
.Understanding operator precedence enables you to write clear and predictable expressions. Take time to review and practice these concepts to master how Java evaluates expressions.
.....
.....
.....