Java Operator Precedence

·

2 min read

Java Operator Precedence Table

Operator Precedence Definition

Operator precedence is not about calculating operations based on priority. When there are multiple operators in a complex expression, operator precedence is used to group them.

This does not determine the order of execution of operations.

Example

Suppose we have the following expression, and the computer needs to decide whether to evaluate a > 0 first or 0 && b.

int a = 1, b = 1;
a > 0 && b - ++a == 1;

Following the Java Operator Precedence Table, we start grouping the expression:

a > 0 && b - ++a == 1;
a > 0 && b - (++a) == 1;
a > 0 && (b - (++a)) == 1;
a > 0 && (b - (++a)) == 1;
(a > 0) && (b - (++a)) == 1;
(a > 0) && ((b - (++a)) == 1);

Now, we evaluate the Logical AND from left to right:

(1 > 0) && ((b - (++a)) == 1);
true && ((b - (++a)) == 1);
true && ((b - (++1)) == 1);

Next, we apply the pre-Increment unary operator, increasing the operand's value by 1 before other calculations:

true && ((b - 2) == 1);
true && ((1 - 2) == 1);
true && (-1 == 1);
true && false;
false;

Increment and Decrement Operators

OperatorDescription
++AIncreases the operand's value by 1 before other calculations
--ADecreases the operand's value by 1 before other calculations
A++Increases the operand's value by 1 after other calculations
A--Decreases the operand's value by 1 after other calculations

Logical OR Operator

The logical OR operator (||) evaluates expressions from left to right. If the first expression is true, it doesn't evaluate the second expression, as only one true result is required.

(1 == 1) || (1 == 2);

In the above case, (1 == 1) is true, so (1 == 2) is not evaluated, and the result is immediately true.

Did you find this article valuable?

Support Eunhan's blog by becoming a sponsor. Any amount is appreciated!