Efficiency when checking multiple conditions with Java

conditional-statements, java, performance

Solution

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.

Problem

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.

Original source

Related problems