Programming and Problem Solving with Java

(やまだぃちぅ) #1
4.2 Conditions and Logical Expressions | 161

lowerCaseString = myString.toLowerCase();
upperCaseString = myString.toUpperCase();


We can use these methods directly in a comparison expression. For example, the fol-
lowing expressions convert word1and word2to the same case before comparing them. It does-
n’t matter whether the strings are both converted to uppercase or both converted to lowercase,
as long as they are both converted using the same method.


word1.toLowerCase().compareTo(word2.toLowerCase()) > 0
word1.toUpperCase().compareTo(word2.toUpperCase()) > 0


If two strings with different lengths are compared and the comparison is equal up to the
end of the shorter string, then the shorter string compares as less than the longer string. For
example, if word2contains "Small", the expression


word2.compareTo("Smaller") < 0


yields true, because the strings are equal up to their fifth character position (the end of the
string on the left), and the string on the right is longer.
If you are just interested in testing the equality of strings, ignoring their case, then
equalsIgnoreCasemethod is a perfect choice. For example, the following expression returnstrue:


"MacPherson".equalsIgnoreCase("macpherson")


Logical Operators In mathematics, the logical (orBoolean)operatorsAND, OR, and NOT take log-


ical expressions as operands. Java uses special symbols for the logical operators: &&(for AND),
||(for OR), and !(for NOT). By combining relational operators with logical operators, we can
make more complex assertions. For example, suppose we want to determine whether a fi-
nal score is greater than 90 anda midterm score is greater than 70. In Java, we would write
the expression this way:


finalScore > 90 && midtermScore > 70


The AND operation (&&) requires both relationships to be true for the overall result to be true.
If either or both of the relationships are false, then the entire result is false.
The OR operation (||) takes two logical expressions and combines them. Ifeitherorboth
are true, the result is true. Both values must be false for the result to be false. Now we can de-
termine whether the midterm grade is an Aorthe final grade is an A. If either the midterm
grade or the final grade equals A, the assertion is true. In Java, we write the expression like this:


midtermGrade == 'A' || finalGrade == 'A'


The &&and ||operators always appear between two expressions; they are binary (two-
operand) operators. The NOT operator (!) is a unary (one-operand) operator. It precedes a sin-
gle logical expression and gives its opposite as the result. For example, if (grade == 'A')is

Free download pdf