Читать книгу OCP Oracle Certified Professional Java SE 17 Developer Study Guide - Jeanne Boyarsky - Страница 165

Ternary Expression and Unperformed Side Effects

Оглавление

As we saw with the conditional operators, a ternary expression can contain an unperformed side effect, as only one of the expressions on the right side will be evaluated at runtime. Let's illustrate this principle with the following example:

int sheep = 1; int zzz = 1; int sleep = zzz<10 ? sheep++ : zzz++; System.out.print(sheep + "," + zzz); // 2,1

Notice that since the left-hand boolean expression was true, only sheep was incremented. Contrast the preceding example with the following modification:

int sheep = 1; int zzz = 1; int sleep = sheep>=10 ? sheep++ : zzz++; System.out.print(sheep + "," + zzz); // 1,2

Now that the left-hand boolean expression evaluates to false, only zzz is incremented. In this manner, we see how the changes in a ternary operator may not be applied if the particular expression is not used.

For the exam, be wary of any question that includes a ternary expression in which a variable is modified in one of the expressions on the right-hand side.

OCP Oracle Certified Professional Java SE 17 Developer Study Guide

Подняться наверх