Programming and Problem Solving with Java

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

sequence of the character set.” For example, in the ASCII subset of the Unicode character set,
all of the uppercase letters are in alphabetical order, as are the lowercase letters, but all of
the uppercase letters come before the lowercase letters. So the expressions


'M' < 'R'


and


'm' < 'r'


have the value true, but


'm' < 'R'


has the value false. All uppercase letters come before any of the lowercase letters.
Of course, we have to be careful about the data types of things that we compare. The safest
approach is to compare identical types: intwith int,doublewith double,charwith char, and
so on. If you mix data types in a comparison, implicit type conversion takes place just as it
does in arithmetic expressions. If you try to compare an intvalue and a doublevalue, for ex-
ample, the computer temporarily converts the intvalue to its doubleequivalent before mak-
ing the comparison. As with arithmetic expressions, it’s wise to use explicit type casting to
make your intentions known:


someDouble >= (double)someInt


If you try to compare a booleanvalue with a numeric value (probably by mistake), the com-
piler will display an error message. Values of type booleancannot be converted to any type
other than String. When a booleanvariable is concatenated with a string, its value is auto-
matically converted to either "true"or "false". No type can be converted to boolean.
Be careful to comparecharvalues only with othercharvalues. For example, the comparisons


'0' < '9'


and


0 < 9


are appropriate, but comparing a digit in quotes (a character) and a digit, such as


'0' < 9


generates an implicit type conversion and a result that probably isn’t what you expect. The
character for the digit '0'is converted to its Unicode intvalue, which is 79, and the com-
parison returns falsebecause 79 is greater than 9.

Free download pdf