Java Reference
In-Depth Information
LISTING 7.1
Continued
24: return;
25: }
26: }
The output of this program is as follows:
0 10 17 13 29 38 2 25 **
120 112 15 19 24 20 30 12 **
106 25 125 69 176 **
Line 15 of the program reads two characters from
code
, the string that was sent to the
readLine()
method, by calling the string's
substring(
int
,
int
)
method.
NOTE
In the
substring()
method of the
String
class, you select a sub-
string in a somewhat counterintuitive way. The first argument spec-
ifies the index of the first character to include in the substring, but
the second argument does not specify the last character. Instead,
the second argument indicates the index of the last character plus
1. A call to
substring(2, 5)
for a string would return the charac-
ters from index position 2 to index position 4.
The two-character substring contains a hexadecimal number stored as a
String
. The
Integer
class method
parseInt
can be used with a second argument to convert this
number into an integer. Use 16 as the argument for a hexadecimal (base 16) conversion,
8 for an octal (base 8) conversion, and so on.
In the
HexReader
application, the hexadecimal
FF
is used to fill out the end of a sequence
and should not be displayed as a decimal value. This is accomplished by using a
try
-
finally
block in lines 13-23 of Listing 7.1.
The
try
-
finally
block causes an unusual thing to happen when the
return
statement is
encountered at line 18. You would expect
return
to cause the
readLine()
method to be
exited immediately.
Because it is within a
try
-
finally
block, the statement within the
finally
block is exe-
cuted no matter how the
try
block is exited. The text
“**”
is displayed at the end of a
line of decimal values.