3

When an if statement contains two (or more) conditions, and the first one fails, does the if statement check the second condition or continue on in the code?

Here are two examples:

int x = 1, y = 2;
if(x == 0 && y == 2)
    System.out.println("Nothing");
if(x == 1 || y == 0)
    System.out.println("Something");

In the first if statement, the conditions should return false, but is y == 2 even tested? And in the second example, the conditions should return true, but is y == 0 tested at all? Or in both cases, after the first condition, the code skips the second condition and continues on in the code?

Thanks in advance.

Alex Salauyou
  • 14,185
  • 5
  • 45
  • 67
Y.A.G.
  • 49
  • 4

3 Answers3

4

&& and || are short-circuit operators, which means the right hand side comparison won't be evaluated if it isn't necessary.

So, we have the following:

  • When using &&, if the left hand side comparison is false, the right hand side comparison is not evaluated.

  • When using ||, if the left hand side comparison is true, the right hand side comparison is not evaluated.


However, when using & and | as logical operators, both sides will always be evaluated.

cassiomolin
  • 124,154
  • 35
  • 280
  • 359
0

Just like @Cassio stated, the second operand will not be evaluated.

Short circuit evaluation is really handy when you need to check for an object existence and validate it's properties, for example.

if (X !=null && X.length !=null) ...
Alex Ureche
  • 351
  • 2
  • 7
0

In && operator both comparison must return true to pass the if condition so if the first one is false the result will be false whatever the second result is.

In || operator if any of the comparison is true, the if result will be true whatever the second result is.

So,

In the AND operator it will test the second comparison if the first one is true and it need to test the second comparison to determine the condition result.

In the OR operator it will test the second comparison if the first one is false and it need to test the second because it could change the condition result if it's true.

Omar Albelbaisy
  • 827
  • 8
  • 15