next up previous
Next: Eliminating the conjunction operator Up: Unit 05 Previous: Example: type of a

Shortcut evaluation of a complex condition

The condition in an if-else statement can be a complex boolean expression, in which the logical operators &&, ||, and ! may appear. We have seen that Java performs a shortcut evaluation of such expressions. In other words, the subexpressions to which the operators are applied are evaluated from left to right as follows:

Consider the case of (e1 && e2). If the value of e1 is false, then the value of the whole expression (e1 && e2) is false, independently of the value of e2. This justifies why in Java e2 is not even evaluated. Similar considerations hold for (e1 || e2).

In general, the fact that Java performs a shortcut evaluation of boolean expressions has to be taken into account and cannot be ignored, since the correctness of the code may depend on that.

Example:

String s;
...
if (s != null && s.length() > 0) {
  System.out.println(s);
}
In this case, when the value of s is null then s.length()>0 is not evaluated and the method length() is not called. Note that, if Java evaluated s.length()>0 also when s is null, then the above code would be wrong, since it would cause trying to access via s a nonexistent object.

Note: In general, if-else statements that make use of complex boolean conditions could be rewritten by making use of nested if-else statements. However, to do so, it may be necessary to duplicate code. We illustrate this in the following separately for && and ||.


next up previous
Next: Eliminating the conjunction operator Up: Unit 05 Previous: Example: type of a