Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Condition evaluation process in Java [duplicate]

Lets say I have the following condition:

if ( myList == null || myList.isEmpty() || xomeX == someY )

What is the order of the evaluation of these conditions? Left or right, right to left or random each time?

If the first one passes, then the others are ignored?

like image 753
Kevin Rave Avatar asked Jul 29 '13 12:07

Kevin Rave


3 Answers

It should be always be left to right except the assignment operator = . You are using short circuit OR operator , hence if the first condition is true , rest of them won't be evaluated.

JLS 15.24:

The conditional-or operator is syntactically left-associative (it groups left-to-right).

At run time, the left-hand operand expression is evaluated first; if the result has type Boolean, it is subjected to unboxing conversion (§5.1.8).

If the resulting value is true, the value of the conditional-or expression is true and the right-hand operand expression is not evaluated.

like image 141
AllTooSir Avatar answered Oct 17 '22 07:10

AllTooSir


From the JLS

At run time, the left-hand operand expression is evaluated first [...] If the resulting value is true, the value of the conditional-or expression is true and the right-hand operand expression is not evaluated.

like image 43
Vincent van der Weele Avatar answered Oct 17 '22 07:10

Vincent van der Weele


if ( myList == null || myList.isEmpty() || xomeX == someY )

Yes the evaluation is from left to right!

and

If the first condition is true next condition is not evaluated. This concept is called Short-circuit evaluation. You can read more on this here. Similar SO question posted earlier is Java logical operator short-circuiting

like image 7
Aniket Thakur Avatar answered Oct 17 '22 08:10

Aniket Thakur