Possible Duplicate:
&& (AND) and || (OR) in Java IF statements
if(foo || bar) {
}
When foo is true, does it even go into bar?
Possible Duplicate:
&& (AND) and || (OR) in Java IF statements
if(foo || bar) {
}
When foo is true, does it even go into bar?
No, ||
uses what is called short-circuit evaluation, otherwise known as minimal evaluation, and will stop evaluating conditions as soon as it finds an expression which evaluates to true
(from left to right).
From the JLS:
15.24. Conditional-Or Operator ||
The conditional-or operator || operator is like | (§15.22.2), but evaluates its right-hand operand only if the value of its left-hand operand is false.
&&
operates in a similar way:
15.23. Conditional-And Operator &&
The conditional-and operator && is like & (§15.22.2), but evaluates its right-hand operand only if the value of its left-hand operand is true.
||
and &&
are both short-circuit logical operators.
When two expressions are joined by OR (||
), if the first one is true, the answer will always be true.
|| true false
true true true
false true false
&&
and ||
stop the evaluation as soon as its result is known. So for example:
if (a == null || a.get() == null)
works well because if a is null, the second part is not evaluated and you don't risk a NullPointerException.
If you want both expressions to be evaluated, you can use the unconditional &
or |
:
if (a == null | a.get() == null)
will evaluate both conditions, whether the first one is true or not.
This thread gives examples of cases when you might want that to happen.