Java Software Solutions, 8e, Global Edition (Lewis/Loftus)
Chapter 8 Arrays
8.1 Multiple-Choice Questions
For the questions below, assume values is an int array that is currently filled to capacity, with
the following values:
1) What is returned by values[3]?
A) 9
B) 12
C) 2
D) 6
E) 3
2) What is the value of values.length?
A) 0
B) 5
C) 6
D) 7
E) 18
3) Which of the following loops would adequately add 1 to each element stored in values?
A) for (j=1; j<values.length; j++) values[j]++;
B) for (j=0; j<values.length; j++) values[j]++;
C) for (j=0; j<=values.length; j++) values[j]++;
D) for (j=0; j<values.length-1; j++) values[j]++;
E) for (j=1; j<values.length-1; j++) values[j]++;
4) The statement System.out.println(values[7]); will
A) output 7
B) output 18
C) output nothing
D) cause an ArrayOutOfBoundsException to be thrown
E) cause a syntax error
5) Which of the following is a legal way to declare and instantiate an array of 10 Strings?
A) String s = new String(10);
B) String[10] s = new String;
C) String[ ] s = new String[10];
D) String s = new String[10];
E) String[ ] s = new String;
6) In Java, arrays are
A) primitive data types
B) objects
C) interfaces
D) primitive data types if the type stored in the array is a primitive data type and objects if the
type stored in the array is an object
E) Strings
7) The “off-by-one” error associated with arrays arises because
A) the first array index is 0 and programmers may start at index 1, or may use a loop that goes
one index too far
B) the last array index is at length + 1 and loops may only iterate to length, missing one
C) the last array element ends at length – 1 and loops may go one too far
D) programmers write a loop that goes from 0 to length – 1 whereas the array actually goes from
1 to length
E) none of the above, the “off-by-one” error has nothing to do with arrays
8) What does the following code do? Assume list is an array of int values, temp is some
previously initialized int value, and c is an int initialized to 0.
for (int j = 0; j < list.length; j++)
if (list[j] < temp) c++;
A) It finds the smallest value and stores it in temp
B) It finds the largest value and stores it in temp
C) It counts the number of elements equal to the smallest value in list
D) It counts the number of elements in list that are less than temp
E) It sorts the values in list to be in ascending order
9) Which of the following lists of numbers would accurately show the array after the first pass
through the Selection Sort algorithm?
A) 9, 4, 12, 2, 6, 8, 18
B) 4, 9, 12, 2, 6, 8, 18
C) 2, 4, 12, 9, 6, 8, 18
D) 2, 4, 6, 8, 9, 12, 18
E) 2, 4, 9, 12, 6, 8, 18
10) Which of the following lists of numbers would accurately show the array after the second
pass of the Selection Sort algorithm?
A) 9, 4, 12, 2, 6, 8, 18
B) 2, 4, 9, 6, 12, 8, 18
C) 2, 4, 12, 9, 6, 8, 18
D) 2, 4, 6, 8, 9, 12, 18
E) 2, 4, 12, 6, 8, 9, 18
11) Which of the following lists of numbers would accurately show the array after the fourth
pass of the Selection Sort algorithm?
A) 9, 4, 12, 2, 6, 8, 18
B) 2, 4, 6, 9, 12, 8, 18
C) 2, 4, 6, 8, 9, 12, 18
D) 2, 4, 6, 9, 8, 12, 18
E) 2, 4, 6, 8, 12, 9, 18
12) How many passes will it take in all for Selection Sort to sort this array?
A) 2
B) 4
C) 5
D) 6
E) 7
13) What does the following code do?
Scanner scan = Scanner.create(System.in);
int value1 = scan.nextInt( );
int value2 = scan.nextInt( );
bars[value1] += value2;
A) adds 1 to the number of bars sold by child value1 and child value2
B) adds 1 to the number of bars sold by child value1
C) adds value1 to the number of bars sold by child value2
D) adds value2 to the number of bars sold by child value1
E) inputs a new value for the number of bars sold by both child value1 and child value2
14) Which of the following code could be used to compute the total number of bars sold by the
children?
A) for (int j=0; j<12; j++) sum += candy[j];
B) for (int j=0; j<12; j++) candy[j] = sum;
C) for (int j=0; j<12; j++) sum = candy[j];
D) for (int j=0; j<12; j++) sum += [j];
E) for (int j=0; j<12; j++) [j] += sum;
15) What does the following method do?
public int question15( )
{
int value1 = 0;
int value2 = 0;
for (int j = 0; j < 12; j++)
if (candy[j] > value1)
{
value1 = candy[j];
value2 = j;
}
return value2;
}
A) It returns the total number of candy bars sold
B) It returns the total number of children who sold 0 candy bars
C) It returns the total number of children who sold more than 0 candy bars
D) It returns the number of candy bars sold by the child who sold the most candy bars
E) It returns the index of the child who sold the most candy bars
16) We compare sorting algorithms by examining
A) the number of instructions executed by the sorting algorithm
B) the number of instructions in the algorithm itself (its length)
C) the types of loops used in the sorting algorithm
D) the amount of memory space required by the algorithm
E) whether the resulting array is completely sorted or only partially sorted
17) Both the Insertion Sort and the Selection Sort algorithms have efficiencies on the order of
________ where n is the number of values in the array being sorted.
A) n
B) n * log n
C) n2
D) n3
E) Insertion sort has an efficiency of n and Selection Sort has an efficiency of n2
18) Consider the array declaration and instantiation: int[ ] arr = new int[5]; Which of the
following is true about arr?
A) It stores 5 elements with legal indices between 1 and 5
B) It stores 5 elements with legal indices between 0 and 4
C) It stores 4 elements with legal indices between 1 and 4
D) It stores 6 elements with legal indices between 0 and 5
E) It stores 5 elements with legal indices between 0 and 5
19) If an int array is passed as a parameter to a method, which of the following would adequately
define the parameter list for the method header?
A) (int[ ])
B) (int a[ ])
C) (int[ ] a)
D) (int a)
E) (a[ ])
20) If int[ ] x = new int[15]; and the statement x[-1] = 0; is executed, then which of the following
Exceptions is thrown?
A) IndexOutOfBoundsException
B) ArrayIndexOutOfBoundsException
C) NegativeArraySizeException
D) NullPointException
E) ArithmeticException
21) Assume that BankAccount is a predefined class and that the declaration BankAccount[ ]
firstEmpireBank; has already been performed. Then the following instruction reserves memory
space for
firstEmpireBank = new BankAccount[1000];
A) a reference variable to the memory that stores all 1000 BankAccount entries
B) 1000 reference variables, each of which point to a single BankAccount entry
C) a single BankAccount entry
D) 1000 BankAccount entries
E) 1000 reference variables and 1000 BankAccount entries
22) The following code accomplishes which of the tasks written below? Assume list is an int
array that stores positive int values only.
int foo = 0;
for (int j =0 ; j < list.length; j++)
if (list[j] > foo) foo = list[j];
A) It stores the smallest value in list (the minimum) in foo
B) It stores the largest value in list (the maximum) in foo
C) It stores every value in list, one at a time, in foo, until the loop terminates
D) It counts the number of elements in list that are greater than foo
E) It counts the number of elements in list that are less than foo
23) If x is a char, and values is an int array, then values[x]
A) causes a syntax error
B) causes an Exception to be thrown
C) casts x as an int based on x’s position in the alphabet (for instance, if x is ‘a’ then it uses 0 and
if x is ‘z’ then it uses 25)
D) casts x as an int based on x’s ASCII value (for instance, if x is ‘a’ then it uses 97 and if x is ‘z’
then it uses 122)
E) casts x as an int based on the digit that is stored in x (for instance, if x is ‘3’ it uses 3) but
throws an exception if x does not store a digit
24) Given the following declarations, which of the following variables are arrays?
int[ ] a, b;
int c, d[ ];
A) a
B) a and b
C) a and d
D) a, b and d
E) a, b, c and d
25) If a and b are both int arrays, then a = b; will
A) create an alias
B) copy all elements of b into a
C) copy the 0th element of b into the 0th element of a
D) return true if each corresponding element of b is equal to each corresponding element of a
(that is, a[0] is equal to b[0], a[1] is equal to b[1] and so forth) and return false otherwise
E) return true if a and b are aliases and return false otherwise
26) The statement int[ ] list = {5, 10, 15, 20};
A) adds 4 int values to array list
B) initializes list to have 20 int values
C) initializes list to have 4 int values
D) declares list but does not initialize it
E) causes a syntax error because it does not include “new int[4]” prior to the list of values
27) To initialize a String array names to store the three Strings “Huey”, “Duey” and “Louie”, you
would do
A) String names = {“Huey”, “Duey”, “Louie”};
B) String[ ] names = {“Huey”, “Duey”, “Louie”};
C) String[ ] names = new String{“Huey”, “Duey”, “Louie”};
D) String names[3] = {“Huey”, “Duey”, “Louie”};
E) String names; names[0] = “Huey”; names[1] = “Duey”; names[2] = “Louie”;
28) A Polygon object in Java is
A) a shape defined as a collection of x, y points
B) a shape defined as a collection of lines
C) a shape defined as a collection of polylines
D) an array of shapes
E) 2 lines connected by 1 common point
29) Which of the following GUI components operates as a group so that only one of the options
can be selected at a time?
A) JCheckBox
B) JButton
C) JRadioButton
D) JButtonGroup
E) all of the above
30) To declare a three-dimensional int array called threeD, which of the following would you
use?
A) int[3] threeD;
B) int[ , , ] threeD;
C) int[ ][ ][ ] threeD;
D) int [ [ [ ] ] ] threeD;
E) int[ ] threeD[3];
31) A polyline in Java is
A) an object
B) a shape defined as a collection of lines
C) a shape defined as a collection of Polygons
D) an array of shapes
E) an shape defined by a collection of points
32) A Polygon object in Java can be
A) built up by using a sequence of addPoint method calls
B) defined by an array of x-y coordinates
C) defined by a polyline
D) A, B, and C all are true
E) only A and B are true
33) The Mouse Events include
A) mousePressed, mouseReleased, mouseClicked, mouseEntered, mouseExited
B) mousePressed, mouseReleased, mouseClicked, mouseEntered, mouseExited, mouseMoved,
mouseDragged
C) mousePressed, mouseReleased, mouseClicked, mouseMoved, mouseDragged
D) mouseClicked, mouseEntered, mouseExited, mouseMoved, mouseDragged
E) mouseMoved, mouseDragged
34) The Mouse Motion Events include
A) mousePressed, mouseReleased, mouseClicked, mouseEntered, mouseExited
B) mousePressed, mouseReleased, mouseClicked, mouseEntered, mouseExited, mouseMoved,
mouseDragged
C) mousePressed, mouseReleased, mouseClicked, mouseMoved, mouseDragged
D) mouseClicked, mouseEntered, mouseExited, mouseMoved, mouseDragged
E) mouseMoved, mouseDragged
35) The Key Events include
A) keyPressed, keyReleased
B) keyPressed, keyReleased, keyTyped
C) keyPressed, keyReleased, keyTyped, keyDown, keyUp
D) keyDown, keyUp, keyTyped
E) none of the above
36) As described in the Software Failure, a race condition bug in a computer program is one in
which
A) a race is held to see which team can finish a computer program first
B) two or more processes that start at the same time finish at different times
C) two or more processes race to create an error
D) two or more processes that share the same data continue running under wrong assumptions
after one of the processes changes the data
E) none of the above
1) Arrays have a built in toString method that returns all of the elements in the array as one
String with “\n” inserted between each element.
2) Java arrays can store primitive types and Strings, but cannot store any other type of Object
other than Strings.
3) A Java main method uses the parameter (String[ ] variable) so that a user can run the program
and supply “command-line” parameters. Since the parameter is a String array, however, the user
does not have to supply any parameters.
4) An array index cannot be a float, double, boolean or String.
5) If the following statement is performed: CD[ ] mycollection = new CD[200]; where CD is a
previously defined class, then mycollection[5] is a CD object.
6) It is possible to sort an array of int, float, double or String, but not an array of an Object class
such as a CD class.
7) To swap the 3rd and 4th elements in the int array values, you would do:
values[3] = values[4];
values[4] = values[3];
8) In Java, an array can only store one type of data. For instance, you cannot create an array that
stores both double and String values.
9) In a two-dimensional array, both dimensions must have the same number of elements, as
in[10][10].
10) An array, when instantiated, is fixed in size, but an ArrayList can dynamically change in size
when new elements are added to it.
11) Just as arrays can only have a fixed number of elements, set at the time the array is declared,
a parameter list also can only have a fixed number of elements, set at the time the method is
declared.
12) Although methods may be declared with a variable length parameter list, class constructors
cannot.
13) A ragged array is a multidimensional array whose initial indices don’t all start at zero.
14) So long as one is only accessing the elements of an ArrayList, its efficiency is about the
same as that of an array. It’s only when one begins to insert or remove elements towards the
front portion of an ArrayList that its efficiency deteriorates.
15) Mouse Events deal with detecting the actions of the buttons on a mouse, among other things,
while Mouse Motion Events deal with the movement of the mouse with/without buttons being
depressed.
16) Regarding the Software Failure: In the 2003 Northeast Blackout, the backup system crashed
for a different reason than the main system, which failed due to a race condition bug in the alarm
system software.
8.3 Free-Form Questions
1) Write a method to compute the average of an int array and return the value as a double. The
int array and the number of elements in the array are both passed as parameters to the method in
that order.
}
2) The length operator can be used to control a for-loop that iterates through each element of an
array, as in
for (int j=0; j<list.length; j++)
However, this is not necessarily safe. Why not?
3) Write a method to compute and return the value of max – min where max is the largest
element of an int array and min is the smallest element of an int array. The method is passed the
int array and an int value that denotes the number of elements in the array. You may assume that
the int array has at least 1 element in it.
4) Write code fragment to swap the two Strings stored by variables a and b.
5) The class Name consists of 4 instance data, String title, String first, String middle, String last.
The class has a constructor that is passed all 4 String values and initializes the class
appropriately, and has 4 methods, each returns one of the four instance data, called returnTitle( ),
returnFirst( ), returnMiddle( ) and returnLast( ). Name[ ] addressBook = new Name[100]; is
performed. Write a method that is passed 4 String parameters corresponding to a Name’s title,
first, middle, and last, and finds this Name in addressBook and returns the index of where this
Name was found, or -1 if the Name was not found. Assume that addressBook stores n entries (n
is an int).
}
6) Demonstrate how the following array is sorted using Insertion Sort. Show the array after each
pass of the outer loop.
[16, 3, 12, 13, 8, 1, 18, 9]
7) Demonstrate how the following array is sorted using Selection Sort. Show the array after each
pass of the outer loop.
[16, 3, 12, 13, 8, 1, 18, 9]
8) Write a code fragment to create a two-dimensional 10×10 array and initialize every element to
be the value of i * j where i and j are the two indices (for instance, element [5][3] is 5 * 3 = 15).
9) Explain how to alter the Selection Sort algorithm so that it sorts in descending order instead of
ascending order.
10) Write an insertion sort method to sort an array of String values (instead of an array of int
values). Assume the array is an instance data of the current class called list, and number is an int
instance data that stores the number of elements currently stored in list.
11) Write a method that takes an array of Strings as a parameter and the number of elements
currently stored in the array, and returns a single String that is the concatenation of all Strings in
the array.
}
12) Assume xArray and yArray are equal length arrays of int values storing num items (num is
also an int). Write a paint method for an Applet that will draw a Polygon shape using this
information. Assume xArray, yArray and num are all instance data of the Applet.
}
13) Write a method to output all elements of a two-dimensional array of int values as a table of
rows and columns. Use “\t” to get elements to line up properly. The method is passed the two-
dimensional array and two int values that denote the number of both dimensions (rows followed
by columns).
19
© Pearson Education Limited, 2015
For the questions below, think of a GUI interface whereby a user can select between food items
and compute a total cost. The food items will be “Burger”, “Fries”, “Soda” and “Cookie”. A
“Burger” costs $2.00, “Fries” cost $1.25, “Soda” costs $1.00 and “Cookie” costs $.70. Assume
jcb1, jcb2, jcb3, jcb4 are JCheckBox elements declared to be private instance data of the GUI
class and jl1 and jl2 are JLabel elements declared to be private instance data of the GUI class.
14) Write code to create a JPanel with 4 JCheckBox GUI components and two JLabels for
output, one that says “Current cost is” and the other that outputs the computed cost based on
which of the food items has been selected.
15) Implement an ItemListener so that a new value is output by the second JLabel every time a
JCheckBox is clicked on.
16) In the RubberLinesPanel example in the text a single LineListener class was defined,
implementing both MouseListener and MouseMotionListener. What are the advantages and
disadvantages of this approach compared to defining two separate classes one for each kind of
Mouse Events?
17) Say that you want to construct a tiny drawing program, where the objects are defined using
line segments. One might use the rubber-banding ideas presented in this chapter to define the
endpoints of line segments, hooking them together into a polyline. One might provide a button
that turns a polyline into a polygon. If this approach is taken, what would be a good way to
represent the data involved in this program: the points, the line segments, the polylines, the
polygons?
18) Write a method public static int[ ][ ] matMult(int[ ][ ] x, int[ ][ ] y) which accepts two
matrices, x and y, and yields their product x * y as its result. Use the normal rules for matrix
multiplication. Be certain to test to see that x and y are compatible before beginning to compute
the matrix product.