next up previous
Next: Conditional expression Up: Unit 05 Previous: Eliminating the conjunction operator

Eliminating the disjunction operator || in a complex condition

The code fragment

if ((x == 1) || (x == 2))
  System.out.println("x equal to 1 or to 2");
else
  System.out.println("x different from 1 and from 2");
corresponds to
if (x == 1)
  System.out.println("x equal to 1 or to 2");
else if (x == 2)
  System.out.println("x equal to 1 or to 2");
else
  System.out.println("x different from 1 and from 2");

In this case, by eliminating the complex condition, the code of the then-branch must be duplicated.

Again, due to shortcut evaluation, the second condition in the || is not evaluated if the first condition is true. And this holds also for the corresponding nested if-else statements.


next up previous
Next: Conditional expression Up: Unit 05 Previous: Eliminating the conjunction operator