Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficiency when checking multiple conditions with Java [duplicate]

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.

like image 947
S. Dave Avatar asked Aug 05 '13 16:08

S. Dave


People also ask

How do you handle multiple conditions in Java?

We can either use one condition or multiple conditions, but the result should always be a boolean. When using multiple conditions, we use the logical AND && and logical OR || operators. Note: Logical AND && returns true if both statements are true. Logical OR || returns true if any one of the statements is true.

How do you handle multiple if conditions?

Use two if statements if both if statement conditions could be true at the same time. In this example, both conditions can be true. You can pass and do great at the same time. Use an if/else statement if the two conditions are mutually exclusive meaning if one condition is true the other condition must be false.

Can you have multiple conditions in a for loop Java?

It is possible to use multiple variables and conditions in a for loop like in the example given below.


1 Answers

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.

like image 52
Kevin Bowersox Avatar answered Sep 28 '22 00:09

Kevin Bowersox