Java Reference
In-Depth Information
Character Testing Using Standard Library Methods
While testing characters using logical operators is a useful way of demonstrating how these operators
work, in practice there is an easier way. The standard Java packages provide a range of standard
methods to do the sort of testing for particular sets of characters such as letters or digits that we have
been doing with
if
statements. They are all available within the class
Character
, which is
automatically available in your programs. For example, we could have written the
if
statement in our
LetterCheck
program as shown in the following example.
Try It Out - Deciphering Characters Trivially
Replace the code body of the
LetterCheck
class with the following code:
if(Character.isUpperCase(symbol)) {
System.out.println("You have the capital letter " + symbol);
} else {
if(Character.isLowerCase(symbol)) {
System.out.println("You have the small letter " + symbol);
} else {
System.out.println("The code is not a letter");
}
}
How It Works
The
isUpperCase()
method returns
true
if the
char
value passed to it is uppercase, and
false
if it is
not. Similarly, the
isLowerCase()
method returns
true
if the
char
value passed to it is lowercase.
The following table shows some of the other methods included in the class
Character
that you may
find useful for testing characters. In each case the argument to be tested is of type
char
, and is placed
between the parentheses following the method name:
Method
Description
isDigit()
Returns the value
true
if the argument is a digit (0 to 9) and
false
otherwise.
isLetter()
Returns the value
true
if the argument is a letter, and
false
otherwise.
isLetterOrDigit()
Returns the value
true
if the argument is a letter or a digit, and
false
otherwise.
isWhitespace()
Returns the value
true
if the argument is whitespace, which is any
one of the characters:
space (' '),
tab ('
\t
'),
newline ('
\n
'),
carriage return ('
\r
'),
form feed ('
\f
')
The method returns
false
otherwise.