Page 199 - Introduction to Programming with Java: A Problem Solving Approach
P. 199

                5.5 Character Class
In the previous section, we mentioned the Character wrapper class, but we didn’t explain it. It’s time to explain it. Often, you’ll need to write programs that manipulate individual characters in a string of text. For example, you might need to read in a phone number and store just the digits, skipping the other characters (dashes, spaces, etc.). To check for digits, use the Character class’s isDigit method. Figure 5.6 shows some of the more popular methods in the Character class, including the isDigit method.
Most of Figure 5.6’s methods are straightforward, but the toUpperCase and toLowerCase methods may need some clarification. Since the two methods are so similar, we’ll clarify only one of the methods, toUpperCase. If you call toUpperCase and pass in a lowercase letter, the method returns the upper- case version of the lowercase letter. But what if you call toUpperCase and pass in an uppercase letter or a nonletter? The method returns the passed-in character, unchanged. And what if you pass in a char variable to toUpperCase instead of a char constant? The method returns the uppercase version of the passed-in char variable, but it does not change the passed-in variable’s value.
As evidenced by the static modifiers in Figure 5.6, most of the Character methods are class methods. Since they’re class methods, you call them by prefacing the method call with the wrapper class’s name. Let’s look at an example. Suppose you’ve got a char variable named middleInitial and you’d like to have its content be converted to an uppercase letter. Here’s a first-cut attempt at changing middle- Initial’s content to an uppercase letter:
Character.toUpperCase(middleInitial);
          Apago PDF Enhancer
5.5 Character Class 165
  public static boolean isDigit(char ch)
Returns true if the specified character is a numerical digit. public static boolean isLetter(char ch)
Returns true if the specified character is a letter of the alphabet. public static boolean isUpperCase(char ch)
Returns true if the specified character is an uppercase letter. public static boolean isLowerCase(char ch)
Returns true if the specified character is a lowercase letter. public static boolean isLetterOrDigit(char ch)
Returns true if the specified character is a letter or a digit. public static boolean isWhitespace(char ch)
Returns true if the specified character is any kind of whitespace (blank, tab, newline). public static char toUpperCase(char ch)
Returns input character as an uppercase character.
public static char toLowerCase(char ch)
Returns input character as a lowercase character.
Figure 5.6 API headings and brief descriptions of some of the methods in the Character class

















































































   197   198   199   200   201