Java Reference
In-Depth Information
Character
Character
isthelargestoftheprimitivetypewrapperclasses,containingmanycon-
stants,aconstructor,manymethods,andatrioofnestedclasses(
Subset
,
UnicodeB-
lock
, and
UnicodeScript
).
brevity,Iignoremuchof
Character
'sUnicode-relatedcomplexity,whichisbeyond
the scope of this chapter.
Character
declares a single
Character(char value)
constructor, which
youusetoinitializea
Character
objectto
value
.Thisconstructoriscomplemented
by
char charValue()
, which returns the wrapped character value.
When you start writing applications, you might codify expressions such as
ch >=
'0' && ch <= '9'
(test
ch
toseeifitcontainsadigit)and
ch >= 'A' && ch
<= 'Z'
(test
ch
to see if it contains an uppercase letter). You should avoid doing so
for three reasons:
• Itistooeasytointroduceabugintotheexpression.Forexample,
ch > '0'
&& ch <= '9'
introducesasubtlebugthatdoesnotinclude
'0'
inthecom-
parison.
• The expressions are not very descriptive of what they are testing.
• TheexpressionsarebiasedtowardLatindigits(0-9)andletters(A-Zanda-z).
Theydonottakeintoaccountdigitsandlettersthatarevalidinotherlanguages.
Forexample,
'\u0beb'
isacharacterliteralrepresentingoneofthedigitsin
the Tamil language.
Character
declaresseveralcomparisonandconversionclassmethodsthataddress
these concerns. These methods include the following:
•
static boolean isDigit(char ch)
returnstruewhen
ch
containsa
digit (typically 0 through 9, but also digits in other alphabets).
•
static boolean isLetter(char ch)
returnstruewhen
ch
contains
a letter (typically A-Z or a-z, but also letters in other alphabets).
•
static boolean isLetterOrDigit(char ch)
returnstruewhen
c
h
containsaletterordigit(typicallyA-Z,a-z,or0-9;butalsolettersordigitsin
other alphabets).
•
static boolean isLowerCase(char ch)
returnstruewhen
ch
con-
tains a lowercase letter.