5

I am trying to brush up on my Java since it has been a long time and started working some warm ups at CodingBat.com. (beware spoilers may follow) ;)

I just did a really simple one that stated:

Given 2 ints, a and b, return true if one if them is 10 or if their sum is 10.

makes10(9, 10) → true
makes10(9, 9) → false
makes10(1, 9) → true

My solution was:

public boolean makes10(int a, int b)
{
  if( a==10 || b==10)
    return true;
  else
  {
      if( (a+b)==10 )
          return true;
       else
          return false;
  }
}

The solution given was:

public boolean makes10(int a, int b) {
  return (a == 10 || b == 10 || a+b == 10);
}

My question is in the case that a=10 or b=10 will the given solution's if statement terminate and return true or will it first complete checking every condition which would require an unneeded addition operation? (i.e. the a+b)

There is a name for this behavior in C++ but for the life of me I cannot remember what it is.

S. Dave
  • 53
  • 3
  • See also: http://stackoverflow.com/questions/7101992/why-do-we-usually-use-not-what-is-the-difference – assylias Aug 05 '13 at 16:03
  • 1
    The behavior is called "Short Circuit" evaluation. – resueman Aug 05 '13 at 16:05
  • While the second method is more efficient, take heart that your code is functionally identical :) – Deactivator2 Aug 05 '13 at 16:06
  • Besides "short-circuiting", I've also seen these called "McCarthy expressions" or "McCarthy evaluation". The C++ standard doesn't seem to use a special name to refer to it, but the Ada standard calls it a "short-circuit control form". – ajb Aug 05 '13 at 16:09
  • Note that there are short-circuit operators (`&&` and `||`) as well as non-short-circuit operators (`&` and `|`) – Steve Kuo Aug 05 '13 at 17:23

2 Answers2

6

The condition will be evaluated until one subcondition evaluates to true. If the first condition evaluates to true the second and third conditions will not be evaluated.

This is nature of the or operator ||.

Consider the following example:

public class Conditions {

    public static boolean isTrue(){
        System.out.println("Is True");
        return true;
    }

    public static boolean isFalse(){
        System.out.println("Is False");
        return false;
    }

    public static void main(String[] args) {
        if(isFalse() || isTrue() || isTrue()){
            System.out.println("Condition passes");
        }
    }
}

Which outputs:

Is False
Is True
Condition passes

Notice that the third condition which calls the method isTrue() is not evaluated.

Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189
0

Any true will decide the outcome of all ORs (A||B||C||D||E)

Any false will decide the outcome of all ANDs (A&&B&&C&&D&&E)

thus at the first occurrence of the deciding value the statement is evaluated.

Community
  • 1
  • 1
rocketboy
  • 9,573
  • 2
  • 34
  • 36