Java Reference
In-Depth Information
public static int
hexCharToDecimal(char ch) {
hex char to decimal
27
28
if
(ch >=
'A'
&& ch <=
'F'
)
to uppercase
29
return
10
+ ch -
'A'
;
30
else
// ch is '0', '1', ..., or '9'
31
return
ch -
'0'
;
32 }
33 }
AB8C
Enter a hex number:
The decimal value for hex number AB8C is 43916
af71
Enter a hex number:
The decimal value for hex number af71 is 44913
The program reads a string from the console (line 11), and invokes the
hexToDecimal
method
to convert a hex string to decimal number (line 14). The characters can be in either lowercase
or uppercase. They are converted to uppercase before invoking the
hexToDecimal
method.
The
hexToDecimal
method is defined in lines 17-25 to return an integer. The length of
the string is determined by invoking
hex.length()
in line 19.
The
hexCharToDecimal
method is defined in lines 27-32 to return a decimal value for a
hex character. The character can be in either lowercase or uppercase. Recall that to subtract
two characters is to subtract their Unicodes. For example,
'5' - '0'
is
5
.
You can create an object for a character using the
Character
class. A
Character
object contains a character value.
Key
Point
Many methods in the Java API require an object argument. To enable the primitive data values
to be treated as objects, Java provides a class for every primitive data type. These classes are
Character
,
Boolean
,
Byte
,
Short
,
Integer
,
Long
,
Float
, and
Double
for
char
,
boolean
,
byte
,
short
,
int
,
long
,
float
, and
double
, respectively. These classes are
called
wrapper classes
because each wraps or encapsulates a primitive type value in an object.
All these classes are in the
java.lang
package, and they contain useful methods for
processing primitive values. This section introduces the
Character
class. The other wrapper
classes will be introduced in Chapter 10, Thinking in Objects.
The
Character
class has a constructor and several methods for determining a character's
category (uppercase, lowercase, digit, and so on) and for converting characters from upper-
case to lowercase, and vice versa, as shown in Figure 9.10.
You can create a
Character
object from a
char
value. For example, the following state-
ment creates a
Character
object for the character
a
.
wrapper class
Character character =
new
Character(
'a'
);
The
charValue
method returns the character value wrapped in the
Character
object. The
compareTo
method compares this character with another character and returns an integer
that is the difference between the Unicode of this character and the Unicode of the other char-
acter. The
equals
method returns
true
if and only if the two characters are the same. For
example, suppose
charObject
is
new Character('b')
:
returns
1
charObject.compareTo(new Character('b'))
returns
0
charObject.compareTo(new Character('c'))
charObject.compareTo(new Character('a'))
returns
-1