You need to convert strings to upper case or lowercase, or to compare strings without regard for case.
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
internationalization. Java provides
significantly more internationalization and localization features
than ordinary languages, a feature that will be covered in Chapter 14. While the equals( )
method tells you if another string is
exactly the same, there is also equalsIgnoreCase( )
, which tells you if all characters are the same
regardless of case. Here, you can’t specify an alternate
locale; the system’s default locale is used.
// Case.java String name = "Java Cookbook"; System.out.println("Normal: " + name); System.out.println("Upper: " + name.toUpperCase( )); System.out.println("Lower: " + name.toLowerCase( )); String javaName = "java cookBook"; // As if it were Java identifiers :-) if (!name.equals(javaName)) System.err.println("equals( ) correctly reports false"); else System.err.println("equals( ) incorrectly reports true"); if (name.equalsIgnoreCase(javaName)) System.err.println("equalsIgnoreCase( ) correctly reports true"); else System.err.println("equalsIgnoreCase( ) incorrectly reports false");
If you run this, it prints the first name changed to uppercase and lowercase, then reports that both methods work as expected.
C:javasrcstrings>java Case Normal: Java Cookbook Upper: JAVA COOKBOOK Lower: java cookbook equals( ) correctly reports false equalsIgnoreCase( ) correctly reports true
18.224.68.28