質問

Ok so I had a weird issue in java and I'm pretty sure this is common to most languages but it was the first time I've encountered something like this. Assume you have two methods.

private boolean foo(int param){ /*some arbitrary stuff*/ }
private boolean bar(int param){ /*some arbitrary stuff*/ }

Each of these methods expect parameters and based on the contents of the parameters they return a true or false based on whether or not something happened. Now I'm going to put them to work.

if(foo(21) || bar(321)){

    //do some other stuff

}

The idea here is to run foo() and bar() and if either of them return true do the other stuff.

It looked fine, it compiled, but when I ran the code things were funky. It was almost as if bar() was not running whenever foo() returned true. So realizing the logical possibility of that I rewrote my code.

boolean a = foo(21);
boolean b = bar(321);

if(a || b){

    //do some other stuff

}

and that fixed my issue. My question is does anyone know why this happens or if there are other practices to ensure the entirety of a conditional is evaluated should it need to?

役に立ちましたか?

解決

Your problem is with short-circuiting. Using || causes the operation to short-circuit once one true value is found. You can instead use | to evaluate both expressions, even if the first is true. Same is true with && and & when it comes to evaluating to false.

if (true || someMethod()) { }

In this statement above, the someMethod() will never be called because true short-circuits the result.

if (true | someMethod()) { }

In this, the someMethod() will be called even though it being true or false is irrelevant to the evaluation of the boolean expression as a whole. See here for more information on short-circuiting in Java: Java logical operator short-circuiting

他のヒント

This is called short-circuiting.

Logical operators will stop evaluating their operands once they know what the result will be.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top