0

When I use the OR operator, only one expression has to be true. Is the first if statement more efficient because java checks only the first expression? Or does java check both?

public class Test {
    public static void main(String args[]) {

        boolean test = true;

        if (test || calculate()) {
            // do something
        }

        if (calculate() || test) {
            // do something
        }
    }

    public static boolean calculate() {
        // processor-intensive algorithm
    }
}
attofi
  • 288
  • 1
  • 6
  • possible duplicate of [&& (AND) and || (OR) in IF statements](http://stackoverflow.com/questions/1795808/and-and-or-in-if-statements) – Amol Bavannavar Jan 28 '15 at 09:26

3 Answers3

9
if (test || calculate())

would never call calculate() when test is true, since || operator is short circuited, so that statement is more efficient when test is true.

Eran
  • 387,369
  • 54
  • 702
  • 768
1

Yes , it is . because calculate() is never called , as long as test is true and it is the contract of || statements.

From §15.24,

The conditional-or operator || operator is like | , but evaluates its right-hand operand only if the value of its left-hand operand is false.

weston
  • 54,145
  • 21
  • 145
  • 203
Santhosh
  • 8,181
  • 4
  • 29
  • 56
0

There are two or operators:

if ( condition | condition2 ){

Here, it will test the second condition regardless of the outcome of the second condition.

if ( condition || condition2 ){

Here, the second condition will only be checked if the first condition returned false.

The same way of double operators is implemented for the 'and' operators & and &&

Stultuske
  • 9,296
  • 1
  • 25
  • 37