Java Reference
In-Depth Information
string. The compareTo() method compares
lexicographically, which means that each char-
acter is compared, one by one. In the process,
uppercase letters are before lowercase letters,
and shorter words are first. For example, 'Java'
is before 'java' and 'compute' is before 'com-
puter'. A similar method, compareToIgnore-
Case(), performs the same function but
ignores the case when comparing two strings.
Table 8-11 displays the return values when the
string, Barb, is compared with other strings.
Table 8-11
Sample Code for the compareTo() Method
CODE
RETURNS
String myObject = “Barb”;
myObject.compareTo(“Anita”)
less than zero
myObject.compareTo(“Barb”)
zero
greater than zero
myObject.compareTo(“Carol”)
Using compareTo() versus compareToIgnoreCase()
The compareTo() method is case sensitive. Use the
compareToIgnoreCase() method to compare two strings
when case does not matter.
In line 198, for example, the text from the Account Number text box is
compared with a null string (""). If that comparison is zero, then the two are
equal, meaning the user has entered nothing in the text box. The multiple uses of
the OR operator ( | | ), when used in an if statement (as it is in Figure 8-27), will
result in true if any of the text boxes are left empty by the user. In line 207, the
Box 5 message box from Table 8-2 on page 491, is called, this time with a
JOptionPane WARNING_MESSAGE icon. The following step codes the
checkFields() method.
To Code the checkFields() Method
1. Enter the code from Figure 8-27.
The TextPad window displays the new code (Figure 8-28).
compareTo()
method
OR operators
code to display
message box
]
return statements
FIGURE 8-28
 
Search WWH ::




Custom Search