Java Reference
In-Depth Information
Try It Out - Deciphering Characters the Easy Way
Replace the outer
if
-
else
loop and its contents in
LetterCheck.java
with the following:
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");
}
}
How It Works
Using the
&&
operator has condensed the example down quite a bit. We now can do the job with two
if
s, and it's certainly easier to follow what's happening.
You might want to note that when the statement in an
else
clause is another
if
, the
if
is sometimes
written on the same line as the
else
, as in:
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");
}
I think the original is clearer, so I prefer not to do this.
&& versus &
So what distinguishes
&&
from
&
? The difference between them is that the conditional
&&
will not bother to
evaluate the right-hand operand if the left-hand operand is
false
, since the result is already determined in
this case to be
false
. This can make the code a bit faster when the left-hand operand is
false
.
For example, consider the following statements:
int number = 50;
if(number<40 && (3*number - 27)>100) {
System.out.println("number = " + number);
}
Here the expression
(3*number
-
27)>100
will never be executed since the expression
number<40
is always
false
. On the other hand, if you write the statements as: