Java Reference
In-Depth Information
The lowercase letters are:
e y l s r i b k j v j h a b z n w b t v
s c c k r d w a m p w v u n q a m p l o
a z g d e g f i n d x m z o u l o z j v
h w i w n t g x w c d o t x h y v z y z
q e a m f w p g u q t r e n n w f c r f
The occurrences of each letter are:
5 a 3 b 4 c 4 d 4 e 4 f 4 g 3 h 3 i 3 j
2 k 3 l 4 m 6 n 4 o 3 p 3 q 4 r 2 s 4 t
3 u 5 v 8 w 3 x 3 y 6 z
The
createArray
method (lines 21-32) generates an array of
100
random lowercase let-
ters. Line 5 invokes the method and assigns the array to
chars
. What would be wrong if you
rewrote the code as follows?
char
[] chars =
new char
[
100
];
chars = createArray();
You would be creating two arrays. The first line would create an array by using
new char[100]
.
The second line would create an array by invoking
createArray()
and assign the reference
of the array to
chars
. The array created in the first line would be garbage because it is no longer
referenced, and as mentioned earlier Java automatically collects garbage behind the scenes.
Your program would compile and run correctly, but it would create an array unnecessarily.
Invoking
getRandomLowerCaseLetter()
(line 28) returns a random lowercase letter.
This method is defined in the
RandomCharacter
class in ListingĀ 6.10.
The
countLetters
method (lines 46-55) returns an array of
26 int
values, each of
which stores the number of occurrences of a letter. The method processes each letter in the
array and increases its count by one. A brute-force approach to count the occurrences of each
letter might be as follows:
for
(
int
i =
0
; i < chars.length; i++)
if
(chars[i] ==
'a'
)
counts[
0
]++;
else if
(chars[i] ==
'b'
)
counts[
1
]++;
...
But a better solution is given in lines 51-52.
for
(
int
i =
0
; i < chars.length; i++)
counts[chars[i] -
'a'
]++;
If the letter (
chars[i]
) is
a
, the corresponding count is
counts['a' - 'a']
(i.e.,
counts[0]
). If the letter is
b
, the corresponding count is
counts['b' - 'a']
(i.e.,
counts[1]
), since the Unicode of
b
is one more than that of
a
. If the letter is
z
, the cor-
responding count is
counts['z' - 'a']
(i.e.,
counts[25]
), since the Unicode of
z
is
25
more than that of
a
.
FigureĀ 7.8 shows the call stack and heap
during
and
after
executing
createArray
. See
Checkpoint Question 7.18 to show the call stack and heap for other methods in the program.
Search WWH ::
Custom Search