Java Reference
In-Depth Information
}
}
LetterCheck2.java
The output should be the same as the previous version of the code.
How It Works
Using the && operator has condensed the example down quite a bit. You 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 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");
}
I think the original is clearer in this particular case, but writing else if can sometimes make the code
easier to follow.
&& versus &
So what distinguishes && from & ? The difference is that the conditional && does not bother to evaluate the
right-hand operand if the left-hand operand is false because 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 is never executed because the expression number<40 is al-
ways false . On the other hand, if you write the statements as
int number = 50;
if(number<40 & (3*number - 27)>100) {
System.out.println("number = " + number);
}
Search WWH ::




Custom Search