Java Reference
In-Depth Information
22 }
23
24
return
decimalValue;
25 }
26
27
public static int
hexCharToDecimal(
char
ch) {
hex char to decimal
check uppercase
28
if
(ch >=
'A'
&& ch <=
'F'
)
29
return
10
+ ch -
'A'
;
30
else
// ch is '0', '1', ..., or '9'
31
return
ch -
'0'
;
32 }
33 }
Enter a hex number: AB8C
The decimal value for hex number AB8C is 43916
Enter a hex number: af71
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
.
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 solu-
tion is to create 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;
}
If you call
max
with
int
parameters, the
max
method that expects
int
parameters will be
invoked; if you call
max
with
double
parameters, the
max
method that expects
double
parameters will be invoked. This is referred to as
method overloading
; that is, two methods
have the same name but different parameter lists within one class. The Java compiler deter-
mines which method to use based on the method signature.
method overloading
Search WWH ::
Custom Search