0

assume I have something simple like this:

if(condition_1 || condition_2) {
do something
}

if condition_1 is true, does java go on and also check condition_2? I'm asking because I know if condition1 is true, condition2 will throw an error and I'm wondering if I need to make two seperate if's.

Billakosama
  • 49
  • 2
  • 11

3 Answers3

6

No. Java uses short-circuiting operators:

  • if (condition1 || condition2) Condition 2 will only be evaluated if condition1 is false.
  • if (condition1 && condition2) Condition 2 will only be evaluated if condition1 is true.

In general: The second condition will only be evaluated if needed.

See Java operators for further information about this.

ifloop
  • 8,079
  • 2
  • 26
  • 35
3
if(condition_1 || condition_2) 
if condition_1 is true, does java go on and also check condition_2?

No!

Google short circuiting concept.

Aniket Thakur
  • 66,731
  • 38
  • 279
  • 289
2

You can also let check both conditions with using just one | token.

if (trueField | isButtonDown()) {
    //
}

Event if the first one is true, the method is called. With two ||, it will not be called.

Ercksen
  • 668
  • 9
  • 23