2
if(fName != null && fName.isEmpty())

In this if expression we have 4 operators

1) . access object member
2) () invoke a method
3) != equality
4) && conditional AND

I have listed as per precedence and all have same associativity i.e left to right

Then why this expression evaluate in order below (to my knowledge)

1) !=
2) &&
3,4) . ()
Amit Yadav
  • 32,664
  • 6
  • 42
  • 57

2 Answers2

3

A logical AND operator (&&) is short circuited. It means the right operand is only evaluated if the left operand evaluates to true.

Therefore fName != null is evaluated first.

If it's true, fName.isEmpty() is evaluated next, and finally the && operator itself is evaluated, since you can't evaluate it before you evaluate its operands.

Here are relevant quotes from the JLS :

15.7 :

The Java programming language guarantees that the operands of operators appear to be evaluated in a specific evaluation order, namely, from left to right.

15.7.1 :

The left-hand operand of a binary operator appears to be fully evaluated before any part of the right-hand operand is evaluated.

15.7.2 :

The Java programming language guarantees that every operand of an operator (except the conditional operators &&, ||, and ? :) appears to be fully evaluated before any part of the operation itself is performed.

Eran
  • 387,369
  • 54
  • 702
  • 768
0
  • In Java, operands are evaluated left to right. So the !=, being part of the left operand of &&, and having higher priority, is evaluated first.
  • The && operator doesn't evaluate its right operand if its left operand is false.

The operator associativity you posted has nothing to do with it.

user207421
  • 305,947
  • 44
  • 307
  • 483