Does Java Evaluate Remaining Conditions After Boolean Result Is Known

Does Java evaluate remaining conditions after boolean result is known?

The || and && operators are short-circuiting.

true || willNeverExecute();
false && willNeverExecute();

How java test conditions

If first condition is true second condition is not evaluated.

If first condition is false also second condition is evaluated.

That's why you can write a code like the following without a NullPointerException

if (str == null || str.length() == 0) {
// do something
}

The operator | (instead of || ) will evaluated both conditions

So the code

if (str == null | str.length() == 0) {
// do something
}

can generate a NullPointerException if str is null

Evaluate at runtime if a series of boolean conditions is valid or not

If all of your bounds are integers, you can convert each of your conditions into a closed range. For example:

  • = x is [x, x]
  • < x is [Integer.MIN_VALUE, x - 1]
  • > x is [x + 1, Integer.MAX_VALUE]

etc.

You can build one of these ranges for each of your input conditions, and then take the intersection of the ranges by calculating the maximum of the lower bounds, and the minimum of the lower bounds.

If the max of the lower bounds <= the min of the upper bounds, the condition can be satisfied.

Example for integers:

boolean canBeSatisfied(Iterable<Pair<enum, Integer>> conditions) {
int maxLower = Integer.MAX_VALUE;
int minUpper = Integer.MIN_VALUE;
for (Pair<enum, Integer> condition : conditions) {
maxLower = Math.max(maxLower, getLowerBound(condition));
minUpper = Math.min(minUpper, getUpperBound(condition));
}
return maxLower <= minUpper;
}

and then define getLowerBound and getUpperBound something like:

int getLowerBound(Pair<enum, Integer> condition) {
switch (condition.first) {
case EQUALS:
case GE:
return condition.second;
case GT:
return condition.second + 1;
case LT: case LE:
return Integer.MIN_VALUE;
}
}

int getUpperBound(Pair<enum, Integer> condition) {
switch (condition.first) {
case EQUALS:
case GE: case GT:
return Integer.MAX_VALUE;
case LT:
return condition.second - 1;
case LE:
return condition.second;
}
}

You can extend the same idea to double bounds, but you need to be a little bit more careful to handle the difference between closed and open bounds.

If you can use Guava, you can do all of this directly with the Range class, using the factory methods to construct appropriate instances of the ranges, and then just taking the intersection of all range instances.

Does all evaluation happen from left to right?

Yes, java will short circuit a conditional with the OR operator from left to right.

At run time, the left-hand operand expression is evaluated first; if
the result has type Boolean, it is subjected to unboxing conversion
(§5.1.8).

If the resulting value is true, the value of the conditional-or
expression is true and the right-hand operand expression is not
evaluated.

If the value of the left-hand operand is false, then the right-hand
expression is evaluated; if the result has type Boolean, it is
subjected to unboxing conversion (§5.1.8). The resulting value becomes
the value of the conditional-or expression.

Two conditions in one if statement does the second matter if the first is false?

It is common for languages (Java and Python are among them) to evaluate the first argument of a logical AND and finish evaluation of the statement if the first argument is false. This is because:

From The Order of Evaluation of Logic Operators,

When Java evaluates the expression d = b && c;, it first checks whether b is true. Here b is false, so b && c must be false regardless of whether c is or is not true, so Java doesn't bother checking the value of c.

This is known as short-circuit evaluation, and is also referred to in the Java docs.

It is common to see list.count > 0 && list[0] == "Something" to check a list element, if it exists.


It is also worth mentioning that if (list.length>2 && list[3] == 2) is not equal to the second case

if (list.length>2){
if (list[3] == 2){
...
}
}

if there is an else afterwards. The else will apply only to the if statement to which it is attached.

To demonstrate this gotcha:

if (x.kind.equals("Human")) {
if (x.name.equals("Jordan")) {
System.out.println("Hello Jordan!");
}
} else {
System.out.println("You are not a human!");
}

will work as expected, but

if (x.kind.equals("Human") && x.name.equals("Jordan")) {
System.out.println("Hello Jordan!");
} else {
System.out.println("You are not a human!");
}

will also tell any Human who isn't Jordan they are not human.

Why isn't counter() called in false && counter()?

This is because && is short-circuiting. When i > 1 evaluates to false, there is no need to check the other side of the logical AND because the resulting expression will always be false. Therefore, the method counter is never run.

To fix this, you can either move counter() to be the first condition, or use the non-short-circuiting &.

In Java, why does the output of b does not change in the case? Is it possible that the using of or lets it only judge the first case?

The OR expression inside the if is getting short-circuited. When the following expression is being evaulated:

(++a > 2) || (++b > 2)

The term with b is only evaluated if the a term is false.

In the first iteration, the a term fails, and the b term is evaluated. After this first iteration, both a and b are equal to 2. For every subsequent iteration, the a term is always true, and the b term therefore is never even evaluated.

Boolean expression order of evaluation in Java?

However, I know some that some compilers will exit the boolean expression entirely if the first condition fails. Is this true with Java?

Yes, that is known as Short-Circuit evaluation.Operators like && and || are operators that perform such operations.

Or is the order of evaluation not guaranteed?

No,the order of evaluation is guaranteed(from left to right)

how does Java posses if statements. (Code flow)

Actually

if (a) {
if (b) {
//stuff
}
}

Is the same thing as

if (a && b) {
//stuff
}

Debugger will stop verification if a is false.
But in more complex statements you should be careful using short circuits.



Related Topics



Leave a reply



Submit