0

Possible Duplicate:
&& (AND) and || (OR) in Java IF statements

if(foo || bar) {

}

When foo is true, does it even go into bar?

Community
  • 1
  • 1
Jaanus
  • 16,161
  • 49
  • 147
  • 202
  • 2
    If `foo` is true, `bar` will be ignored. It's short-circuit evaluation. – Baz Aug 27 '12 at 11:55
  • 1
    There is little point in questions like this. Why not just [try](http://ideone.com/m35Sl)? – Karolis Juodelė Aug 27 '12 at 12:01
  • @Karolis: Because trying will show you the behaviour of the Java VM you are running at now and not necessarily the specified behaviour. – jarnbjo Aug 27 '12 at 12:33
  • @jarnbjo But you'd have a broken JVM if its behaviour would be different from what's specified in the Java Language Specification. Especially if something basic like this would not work, it would be really, really broken. – Jesper Aug 27 '12 at 12:48
  • @Jesper: And the problem is? If some behaviour is specified, it will of course work in any VM, if the VM is not broken. If you observe a behaviour on one VM, you cannot however conclude the other way around and assume the behaviour to be specified and the same on all other VMs. – jarnbjo Aug 27 '12 at 13:40

3 Answers3

7

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.

João Silva
  • 89,303
  • 29
  • 152
  • 158
1

|| 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
assylias
  • 321,522
  • 82
  • 660
  • 783
Mohammod Hossain
  • 4,134
  • 2
  • 26
  • 37
1

&& 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.

Community
  • 1
  • 1
assylias
  • 321,522
  • 82
  • 660
  • 783