Boolean expression order of evaluation in Java?
Solution 1:
However, I know some that some compilers will exit the boolean expression entirely if the first condition fails. Is this true with Java?
Yes, that is known as Short-Circuit evaluation.Operators like &&
and ||
are operators that perform such operations.
Or is the order of evaluation not guaranteed?
No,the order of evaluation is guaranteed(from left to right)
Solution 2:
Java should be evaluating your statements from left to right. It uses a mechanism known as short-circuit evaluation to prevent the second, third, and nth conditions from being tested if the first is false.
So, if your expression is myContainer != null && myContainer.Contains(myObject)
and myContainer
is null, the second condition, myContainer.Contains(myObject)
will not be evaluated.
Edit: As someone else mentioned, Java in particular does have both short-circuit and non-short-circuit operators for boolean conditions. Using &&
will trigger short-circuit evaluation, and &
will not.
Solution 3:
James and Ed are correct. If you come across a case in which you would like all expressions to be evaluated regardless of previous failed conditions, you can use the non-short-circuiting boolean operator &
.