Java Reference
In-Depth Information
Enter a decimal number:
The hex number for decimal 1234 is 4D2
1234
line#
decimal
hex
hexValue
toHexChar(hexValue)
19
1234
""
22
2
iteration 1
23
"2"
2
24
77
22
13
iteration 2
23
"D2"
D
24
4
22
4
iteration 3
23
"4D2"
4
24
0
The program uses the
decimalToHex
method (lines 18-28) to convert a decimal integer to a
hex number as a string. The method gets the remainder of the division of the decimal integer
by
16
(line 22). The remainder is converted into a character by invoking the
toHexChar
method (line 23). The character is then appended to the hex string (line 23). The hex string is
initially empty (line 19). Divide the decimal number by
16
to remove a hex digit from the
number (line 24). The
decimalToHex
method repeatedly performs these operations in a loop
until quotient becomes
0
(lines 21-25).
The
toHexChar
method (lines 31-36) converts a
hexValue
between
0
and
15
into a hex
character. If
hexValue
is between
0
and
9
, it is converted to
(char)(hexValue + '0')
(line 33). Recall that when adding a character with an integer, the character's Unicode is used in
the evaluation. For example, if
hexValue
is
5
,
(char)(hexValue + '0')
returns
5
. Simi-
larly, if
hexValue
is between
10
and
15
, it is converted to
(char)(hexValue - 10 +
'A')
(line 35). For instance, if
hexValue
is
11
,
(char)(hexValue - 10 + 'A')
returns
B
.
5.15
✓
✓
What is the return value from invoking
toHexChar(5)
? What is the return value
from invoking
toHexChar(15)
?
Check
Point
5.16
What is the return value from invoking
decimalToHex(245)
? What is the return
value from invoking
decimalToHex(3245)
?
Overloading methods enables you to define the methods with the same name as long
as their signatures are different.
Key
Point
The
max
method that was used earlier works only with the
int
data type. But what if you need to
determine which of two floating-point numbers has the maximum value? The solution is to cre-
ate another method with the same name but different parameters, as shown in the following code:
public static double
max(
double
num1,
double
num2) {
if
(num1 > num2)
return
num1;
else
return
num2;
}