Short circuit evaluation of boolean expressions

Java uses short circuit (sometimes called lazy) evaluation of boolean expressions. Specificially:

• If the left operand of an && (and) evaluates to false, the expression evaluates to false. The right operand is not evaluated.
• If the left operand of an || (or) evaluates to true, the expression evaluates to true. The right operand is not evaluated.

This behavior matters when evaluating the right operand would cause a runtime error or a change in state.

Example 1

int x = 5, y = 0;

System.out.println(y == 0 || x / y > 1);

The example prints: true

y == 0, the left operand of the ||, is evaluated first. 0 == 0 evaluates to true. The entire expression evaluates to true.

x / y > 1, the right operand of the ||, is not evaluated. This is important since evaluating 5 / 0 > 1 would result in an ArithmeticException for dividing by 0.

Example 2

String name = "Brandon";
//             0123456

System.out.println(name.length() >= 7 && name.substring(6, 7).equals("n"));

The example prints: true

name.length() >= 7, the left operand of the && is evaluated first. 7 >= 7 evaluates to true.

name.substring(6, 7).equals("n"), the right operand of the && is evaluated next. "n".equals("n") evaluates to true.

The entire expression evaluates to true.

Example 3

String name = "Horn";
//      0123

System.out.println(name.length() >= 7 && name.substring(6, 7).equals("n"));

The example prints: false

The boolean expression is the same as in Example 2; however, the String is shorter.

name.length() >= 7, the left operand of the && is evaluated first. 4 >= 7 evaluates to false. The entire expression evaluates to false.

name.substring(6, 7).equals("n"), the right operand of the &&, is not evaluated. This is important since evaluating "Horn".substring(6, 7) would result in a StringIndexOutOfBoundsException for accessing the non-existent character at index 6.