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

Conditional Operators

Оглавление

Next, we present the conditional operators, && and ||, in Table 2.10.

TABLE 2.10 Conditional operators

Operator Example Description
Conditional AND a && b Value is true only if both values are true. If the left side is false, then the right side will not be evaluated.
Conditional OR c || d Value is true if at least one of the values is true. If the left side is true, then the right side will not be evaluated.

The conditional operators, often called short-circuit operators, are nearly identical to the logical operators, & and |, except that the right side of the expression may never be evaluated if the final result can be determined by the left side of the expression. For example, consider the following statement:

int hour = 10; boolean zooOpen = true || (hour < 4); System.out.println(zooOpen); // true

Referring to the truth tables, the value zooOpen can be false only if both sides of the expression are false. Since we know the left side is true, there's no need to evaluate the right side, since no value of hour will ever make this code print false. In other words, hour could have been -10 or 892; the output would have been the same. Try it yourself with different values for hour!

OCP Oracle Certified Professional Java SE 17 Developer Study Guide

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