O'Reilly logo

Java Cookbook by Ian F. Darwin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Controlling Case

Problem

You need to convert strings to upper case 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 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:\t" + name); System.out.println("Upper:\t" + name.toUpperCase( )); System.out.println("Lower:\t" + 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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required