Java 7 for Absolute Beginners

(nextflipdebug5) #1
CHAPTER 4 ■ OPERATORS

Listing 4-21. Chaining logical AND operators


if (3 > 2 && 2 > 1 && 1 > 0) {
System.out.println("Numbers work as expected");
}


The result of the middle comparison (2 > 1) serves as an operator to both of the logical AND
operators. That kind of chaining is common in all programming problems, regardless of language. We're
fortunate that Java makes it easy to do.


Logical OR Operator (||)


The logical AND operator (||) returns true if either of its arguments are true and false only if both
arguments are false. Otherwise, it works just like the logical AND operator.
Listing 4-22 is an example.


Listing 4-22. Logical AND operator (&&)


if (2 > 1 || 1 < 0) {
System.out.println("Numbers work as expected");
}


As with logical AND operators, you can chain multiple logical AND operators, as shown in Listing
4-23.


Listing 4-23. Chaining logical AND operators


if (3 > 2 || 2 < 1 || 1 < 0) {
System.out.println("Numbers work as expected");
}


■ Note Eclipse warns us that we have dead code within the comparisons when we run this code. Because 2 is


always greater than 1, the JVM won't try to compare 1 to 0, so Eclipse tells us that we can remove that


comparison. Of course, real-world examples check to make sure that a data stream isn't null and has at least


some content. Listing 4-24 contains that code.


Listing 4-24. A more realistic use for the logical OR operator


if (dataStream == null || dataStream.length == 0) {
log.error("No data available!");
}


Again, the equality operators have higher precedence, so we don't need additional parentheses.
Free download pdf