Java Reference
In-Depth Information
TABLE 3-3
:
Methods Useful for Testing Characters
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 follow-
ing characters:
space (
' '
)
tab (
'\t'
)
newline (
'\n'
)
carriage return (
'\r'
)
form feed (
'\f'
)The method returns
false
otherwise.
You can find information on other methods in the
Character
class in the JDK documentation for the
class.
THE CONDITIONAL OPERATOR
The
conditional operator
is sometimes called a
ternary operator
because it involves three operands. It is
best understood by looking at an example. Suppose you have two variables of type
int
with the names
yourAge
and
myAge
, and you want to assign the greater of the values stored in
yourAge
and
myAge
to a third
variable,
older
, which is also of type
int
. You can do this with the following statement:
older = yourAge > myAge ? yourAge : myAge;
The conditional operator has a logical expression as the first of its three operands — in this case, it is the
expression
yourAge>myAge
. If this expression is
true
, the operand that follows the
?
symbol — in this case,
yourAge
— is evaluated to produce the value resulting from the operation. If the expression
yourAge>myAge
is
false,
the third operand that comes after the colon — in this case,
myAge
— is evaluated to produce the
value from the operation. Thus, the result of this conditional expression is
yourAge
, if
yourAge
is greater
than
myAge
, and
myAge
otherwise. This value is then stored in the variable
older
. The use of the conditional
operator in this assignment statement is equivalent to the
if
statement:
if(yourAge > myAge) {
older = yourAge;
} else {
older = myAge;
}
Remember, though, the conditional operator is an operator and not a statement, so you can use it in a
more complex expression involving other operators.
The conditional operator can be written generally as:
logical_expression ? expression1 : expression2