Reputation: 288
When I use the OR operator, only one expression has to be true. Is the first if statement more efficient because java checks only the first expression? Or does java check both?
public class Test {
public static void main(String args[]) {
boolean test = true;
if (test || calculate()) {
// do something
}
if (calculate() || test) {
// do something
}
}
public static boolean calculate() {
// processor-intensive algorithm
}
}
Upvotes: 0
Views: 132
Reputation: 8197
Yes , it is . because calculate()
is never called , as long as test
is true and it is the contract of ||
statements.
From §15.24,
The conditional-or operator || operator is like | , but evaluates its right-hand operand only if the value of its left-hand operand is false.
Upvotes: 1
Reputation: 9437
There are two or operators:
if ( condition | condition2 ){
Here, it will test the second condition regardless of the outcome of the second condition.
if ( condition || condition2 ){
Here, the second condition will only be checked if the first condition returned false.
The same way of double operators is implemented for the 'and' operators & and &&
Upvotes: 0
Reputation: 393856
if (test || calculate())
would never call calculate()
when test
is true, since ||
operator is short circuited, so that statement is more efficient when test
is true.
Upvotes: 9