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

Logical Operators

Оглавление

If you have studied computer science, you may have already come across logical operators before. If not, no need to panic—we'll be covering them in detail in this section.

The logical operators, (&), (|), and (^), may be applied to both numeric and boolean data types; they are listed in Table 2.9. When they're applied to boolean data types, they're referred to as logical operators. Alternatively, when they're applied to numeric data types, they're referred to as bitwise operators, as they perform bitwise comparisons of the bits that compose the number. For the exam, though, you don't need to know anything about numeric bitwise comparisons, so we'll leave that educational aspect to other books.

TABLE 2.9 Logical operators

Operator Example Description
Logical AND a & b Value is true only if both values are true.
Logical inclusive OR c | d Value is true if at least one of the values is true.
Logical exclusive OR e ^ f Value is true only if one value is true and the other is false.

You should familiarize yourself with the truth tables in Figure 2.2, where x and y are assumed to be boolean data types.


FIGURE 2.2 The logical truth tables for &, |, and ^

Here are some tips to help you remember this table:

 AND is only true if both operands are true.

 Inclusive OR is only false if both operands are false.

 Exclusive OR is only true if the operands are different.

Let's take a look at some examples:

boolean eyesClosed = true; boolean breathingSlowly = true; boolean resting = eyesClosed | breathingSlowly; boolean asleep = eyesClosed & breathingSlowly; boolean awake = eyesClosed ^ breathingSlowly; System.out.println(resting); // true System.out.println(asleep); // true System.out.println(awake); // false

You should try these out yourself, changing the values of eyesClosed and breathingSlowly and studying the results.

OCP Oracle Certified Professional Java SE 17 Developer Study Guide

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