Java Reference
In-Depth Information
Controlling Case
Problem
You need to convert strings to uppercase or lowercase, or to compare strings without regard
for case.
Solution
The String class has a number of methods for dealing with documents in a particular case.
toUpperCase() and toLowerCase() each return a new string that is a copy of the current
string, but converted as the name implies. Each can be called either with no arguments or
with a Locale argument specifying the conversion rules; this is necessary because of interna-
tionalization. Java provides significantly more internationalization and localization features
than ordinary languages, a feature that is covered in Chapter 15 . Whereas the equals()
method tells you if another string is exactly the same, equalsIgnoreCase() tells you if all
characters are the same regardless of case. Here, you can't specify an alternative locale; the
system's default locale is used:
String name = "Java Cookbook" ;
System . out . println ( "Normal:\t" + name );
System . out . println ( "Upper:\t" + name . toUpperCase ());
System . out . println ( "Lower:\t" + name . toLowerCase ());
String javaName = "java cookBook" ; // If it were Java identifiers :-)
iif (! name . equals ( javaName ))
System . err . println ( "equals() correctly reports false" );
else
else
System . err . println ( "equals() incorrectly reports true" );
iif ( name . equalsIgnoreCase ( javaName ))
System . err . println ( "equalsIgnoreCase() correctly reports true" );
else
else
System . err . println ( "equalsIgnoreCase() incorrectly reports false" );
If you run this, it prints the first name changed to uppercase and lowercase, then it reports
that both methods work as expected:
C:\javasrc\strings> java strings.Case
Normal: Java Cookbook
Upper: JAVA COOKBOOK
Search WWH ::




Custom Search