Java Reference
In-Depth Information
Logical AND Operations
You can use either of the AND operators,
&&
or
&
, where you have two logical expressions that must both be
true
for the result to be
true
— that is, you only want to be rich and healthy. Either AND operator produces
the same result from the logical expression. I come back to how they differ in a moment. First, let's explore
how they are used. All of the following discussion applies equally well to
&
as well as to
&&
.
Let's see how logical operators can simplify the last example. You could use the
&&
operator if you test
a variable of type
char
to determine whether it contains an uppercase letter or not. The value being tested
must be both greater than or equal to '
A
' AND less than or equal to '
Z
'. Both conditions must be
true
for
the value to be a capital letter. Taking the example from our previous program, with a value stored in a
char
variable
symbol
, you could implement the test for an uppercase letter in a single
if
by using the
&&
operator:
if(symbol >= 'A' && symbol <= 'Z')
System.out.println("You have the capital letter " + symbol);
If you look at the precedence table in Chapter 2, you see that the relational operators are executed before
the
&&
operator, so no parentheses are necessary. Here, the output statement is executed only if both of the
conditions combined by the operator
&&
are
true
. However, as I have said before, it is a good idea to add
parentheses if they make the code easier to read. It also helps to avoid mistakes.
In fact, the result of an
&&
operation is very simple. It is
true
only if both operands are
true
; otherwise,
the result is
false
.
You can now rewrite the set of
if
s from the last example.
TRY IT OUT: Deciphering Characters the Easy Way
You can replace the outer
if
-
else
loop and its contents in
LetterCheck.java
as shown in the following
code:
public class LetterCheck2 {
public static void main(String[] args) {
char symbol = 'A';
symbol = (char)(128.0*Math.random()); // Generate a random
character
if(symbol >= 'A' && symbol <= 'Z') {
// Is it a capital
letter
System.out.println("You have the capital letter " + symbol);
} else {
if(symbol >= 'a' && symbol <= 'z') {
// or is it a small
letter?
System.out.println("You have the small letter " + symbol);
} else {
// It is not less
than z
System.out.println("The code is not a letter");
}
}