Java Reference
In-Depth Information
The createArray method (lines 21-32) generates an array of 100 random lowercase letters.
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 cre-
ate an array unnecessarily.
Invoking getRandomLowerCaseLetter() (line 28) returns a random lowercase letter.
This method is defined in the RandomCharacter class in Listing 5.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 corre-
sponding count is counts['z' - 'a'] (i.e., counts[25] ), since the Unicode of z is 25
more than that of a .
Figure 6.9 shows the call stack and heap during and after executing createArray .
See Checkpoint Question 6.16 to show the call stack and heap for other methods in the
program.
Stack
Heap
Stack
Heap
Space required for the
createArray method
Array of 100
characters
Array of 100
characters
char[] chars : ref
Space required for the
main method
Space required for the
main method
char[] chars : ref
char[] chars : ref
(a) Executing
createArray in line 5
(b) After exiting
createArray in line 5
F IGURE 6.9 (a) An array of 100 characters is created when executing createArray .
(b) This array is returned and assigned to the variable chars in the main method.
 
Search WWH ::




Custom Search