Java Operator Precedence

Java Operator Precedence

Java Operator Precedence

Java Operator Precedence:

Java Operator Precedence refers to the order in which operators are evaluated in an expression. The operator with the highest precedence is evaluated first, followed by the operator with the second-highest precedence, and so on.

The following is the order of operator precedence in Java (from highest to lowest):

  1. Postfix operators: ++, —
  2. Unary operators: +, -, !, ~, ++, –, (type)
  3. Multiplicative operators: *, /, %
  4. Additive operators: +, –
  5. Shift operators: <<, >>, >>>
  6. Relational operators: <, <=, >, >=, instanceof
  7. Equality operators: ==, !=
  8. Bitwise AND operator: &
  9. Bitwise XOR operator: ^
  10. Bitwise OR operator: |
  11. Logical AND operator: &&
  12. Logical OR operator: ||
  13. Ternary operator: ? :
  14. Assignment operator: =, +=, -=, *=, /=, %=, &=, ^=, |=, <<=, >>=, >>>=

In an expression, if two or more operators have the same precedence, their associativity determines the order of evaluation. Associativity can be left-to-right or right-to-left. For example, the arithmetic operators (+, -, *, /) have left-to-right associativity, which means that they are evaluated from left to right.

Here’s an example that demonstrates operator precedence:

				
					public class OperatorPrecedenceExample {
    public static void main(String[] args) {
        int a = 5, b = 10, c = 15;
booleanresult;

        result = a + b * c < b - a * c;
System.out.println(result);

        result = a == b || a < c && b >c;
System.out.println(result);

        result = !(a != b) && (c > b || c < a);
System.out.println(result);
    }
}

				
			

In the first expression, the multiplication operator (*) has a higher precedence than the addition operator (+), so b * c is evaluated first, then added to a, and then compared to b – a * c.

In the second expression, the AND operator (&&) has a higher precedence than the OR operator (||), so a < c and b > c are evaluated first, and then their results are OR’ed together with the result of a == b.

In the third expression, the NOT operator (!) has the highest precedence, so it is evaluated first, followed by the inequality operator (!=). Then the AND operator (&&) is evaluated, followed by the OR operator (||).

Join To Get Our Newsletter
Spread the love