Operator Precedence in Java

Operator Precedence in Java
  • Java has well-defined rules for Operator Precedence.
  • It is used in an expression are evaluated when the expression has several operators. 
  • For example, multiplication and division have higher precedence than addition and subtraction. 
Precedence order:
  • When two operators share an operand the operator with the higher precedence goes first.
  • For example: 
1 + 2 * 3 is treated as 1 + (2 * 3)
1 * 2 + 3 is treated as (1 * 2) + 3
  • Due, multiplication has a higher precedence than addition.
Associativity: 
  • When an expression has two operators with the same precedence, the expression is evaluated according to its associativity.
  • For example:
x = y = z = 17 is treated as x = (y = (z = 17))
  • For Example:
72 / 2 / 3 is treated as (72 / 2) / 3 since the / operator has left-to-right associativity

Precedence and associativity of Java operators:
Figure:

Order of evaluation of subexpressions:
  • In Java, subexpressions are evaluated from left to right.
  • For Example:
A() + B() * C(D(), E())
  • So, evaluated in the order A(), B(), D(), E(), and C()
Short-circuiting:
  • When using the conditional and or operators (&& and ||), Java does not evaluate the second operand unless it is necessary to resolve the result.
For Example:(s != null && s.length() < 10)

Exercises:

  • Q - What is the result of the following code fragment?

int x = 5;
int y = 10;
int z = ++x * y--;


  • Q - What is the result of the following code fragment? Explain.

System.out.println("1 + 2 = " + 1 + 2);
System.out.println("1 + 2 = " + (1 + 2));


  • Q - What does the following code fragment print?

System.out.println(1 + 2 + "abc");
System.out.println("abc" + 1 + 2);

Thanks a lot for query or your valuable suggestions related to the topic.

Previous Post Next Post

Contact Form