Computer Science Test Bank
Computer Science Test Bank
Maha Otaibi 1
10. Which of the following statements about interfaces is NOT true?
a) Interfaces can make code more reusable.
b) An interface provides no implementation.
c) A class can implement only one interface type.
d) Interfaces can reduce the coupling between classes.
Answer: c
12. Suppose you are writing an interface called Resizable, which includes one void method called resize.
_____________________________
{
// code to encrypt the text using encryption key goes here
}
}
Which of the following method headers should be used to complete the SecretText class?
Maha Otaibi 2
15. Consider the following code snippet:
public interface Sizable
{
int LARGE_CHANGE = 100;
int SMALL_CHANGE = 20;
void changeSize();
}
Which of the following statements is true?
a) LARGE_CHANGE and SMALL_CHANGE are automatically public static final.
b) LARGE_CHANGE and SMALL_CHANGE are instance variables
c) LARGE_CHANGE and SMALL_CHANGE must be defined with the keywords private static final.
d) LARGE_CHANGE and SMALL_CHANGE must be defined with the keywords public static final.
Answer: a
17. Which of the following is true regarding a class and interface types?
a) You can convert from a class type to any interface type that is in the same package as the class.
b) You can convert from a class type to any interface type that the class implements.
c) You can convert from a class type to any interface type that the class defines.
d) You cannot convert from a class type to any interface type.
Answer: b
Maha Otaibi 3
Which of the following statements is correct?
a)
Coin dime = new Coin(0.1, "dime");
Measurable x = dime;
b)
Coin dime = new Coin(0.1, "dime");
Dataset x = dime;
c)
Coin dime = new Coin(0.1, "dime");
DataSet x == (Measureable)dime;
d)
Coin dime = new Coin(0.1, "dime");
BankAccount x = dime;
Answer: a
19. Which of the following statements about converting between types is true?
a) When you cast number types, you take a risk that an exception will occur.
b) When you cast number types, you will not lose information.
c) When you cast object types, you take a risk of losing information.
d) When you cast object types, you take a risk that an exception will occur.
Answer: d
21. You have created a class named Motor that implements an interface named Measurable. You have declared a variable of
type Measureable named motorTemperature. Which of the following statements is true?
a) The object to which motorTemperature refers has type Measurable.
b) The object to which motorTemperature refers has type Motor.
c) This declaration is illegal.
d) You must construct a motorTemperature object from the Measurable interface.
Answer: b
22. ____ occurs when a single class has several methods with the same name but different parameter types.
a) Casting
b) Polymorphism
c) Overloading
d) Instantiation
Answer: c
Maha Otaibi 4
24. If you have multiple classes in your program that have implemented the same interface in different ways, how is the correct
method executed?
a) The Java virtual machine must locate the correct method by looking at the class of the actual object.
b) The compiler must determine which method implementation to use.
c) The method must be qualified with the class name to determine the correct method.
d) You cannot have multiple classes in the same program with different implementations of the same interface.
Answer: a
a) increaseSize()
b) decreaseSize()
c) display()
d) display(5)
Answer: c
26. Which of the following can potentially be changed when implementing an interface?
a) The parameters of a method in the interface.
b) The name of a method in the interface.
c) The return type of a method in the interface.
d) You cannot change the name, return type, or parameters of a method in the interface.
Answer: d
Maha Otaibi 5
28. The method below is designed to print the smaller of two values received as arguments. Select the correct expression to
complete the method.
31. You wish to implement a callback method for an object created from a system class that you cannot change. What approach
does the textbook recommend to accomplish this?
What parameter declaration can be used to complete the callback measure method?
a) Object anObject
b) String anObject
c) Object aString
d) String aString
Answer: a
Maha Otaibi 6
34. Assuming that interface Resizable is declared elsewhere, consider the following class declaration:
Which of the following declarations can be used to complete the main method?
a) Resizable something = new Resizable();
b) Resizable something = new SizeModifier();
c) Resizable something = new InnerClassExample();
d) SizeModifier something = new Resizable();
Answer: b
36. A/an ____ class defined in a method signals to the reader of your program that the class is not interesting beyond the scope of
the method.
a) A class cannot be defined within a method
b) abstract
c) interface
d) inner
Answer: d
myImage.add(new Rectangle(10,10,10,10));
a) The mock class should be an interface that will be implemented by the real class.
b) The real class should be an interface that will be implemented by the mock class.
c) Interfaces are not involved when using mock classes.
d) An interface should be implemented by both the real class and the mock class to guarantee that the mock class accurately
simulates the real class when used in a program.
Answer: d
42. Which of the following statements about events and graphical user interface programs is true?
a) Your program must instruct the Java window manager to send it notifications about specific types of events to which the
program wishes to respond.
b) The Java window manager will automatically send your program notifications about all events that have occurred.
c) Your program must respond to notifications of all types of events that are sent to it by the Java window manager.
D) Your program must override the default methods to handle events.
Answer: a
44. ____ are generated when the user presses a key, clicks a button, or selects a menu item.
a) Listeners
b) Interfaces.
c) Events.
d) Errors.
Answer: c
45. A/an ____ belongs to a class whose methods describe the actions to be taken when a user clicks a user-interface graphical
object.
a) Event listener
b) Event source
c) Action listener
d) Action method
Answer: a
47. To respond to a button event, a listener must supply instructions for the ____ method of the ActionListener interface.
a) actionEvent.
b) actionPerformed
c) eventAction
d) eventResponse
Answer: b
48. To associate an event listener with a JButton component, you must use the ___ method of the JButton class.
a) addEventListener.
b) addActionListener.
c) addButtonListener.
d) addListener
Answer: b
Maha Otaibi 8
49. The methods of a/an ____ describe the actions to be taken when an event occurs.
a) event source
b) event listener
c) event interface
d) action source
Answer: b
50. When an event occurs, the event source notifies all ____.
a) components
b) panels
c) interfaces
d) event listeners
Answer: d
a) text area
b) table
c) panel
d) rectangle
Answer: c
a)
public interface AccountListener()
{
void actionPerformed(AccountEvent event);
}
b)
public interface AccountListener()
{
void actionPerformed(AccountEvent);
}
c)
public interface AccountListener
{
void actionPerformed(AccountEvent event);
}
d)
public abstract AccountListener
{
void actionPerformed(AccountEvent event);
}
Answer: c
a) frame.add(panel);
b) frame.add(JPanel panel);
c) frame.addComponent(panel);
d) frame.addComponent(JPanel panel);
Answer: a
Maha Otaibi 9
55. Consider the following code snippet:
import ____________________
import java.awt.event.ActionListener;
/**
An action listener that prints.
*/
public class ClickListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
System.out.println("I was clicked.");
}
}
Which of the following statements will complete this code?
a) java.swing.event.ActionEvent;.
b) javax.swing.event.ActionEvent;
c) javax.awt.event.ActionEvent;
d) java.awt.event.ActionEvent;
Answer: d
56. Event listeners are often installed as ____ classes so that they can have access to the surrounding fields, methods, and final
variables.
a) Inner
b) Interface
c) Abstract
d) Helper
Answer: a
a) An inner class may not be declared within a method of the enclosing scope.
b) An inner class may only be declared within a method of the enclosing scope.
c) An inner class can access variables from the enclosing scope only if they are passed as constructor or method parameters.
d) The methods of an inner class can access variables declared in the enclosing scope.
Answer: d
Maha Otaibi 10
59. An inner class can access local variables from the enclosing scope only if they are declared as ____.
a) private
b) public
c) static
d) final
Answer: b
60. Which of the following code statements creates a graphical button which has "Calculate" as its label ?
61. To build a user interface that contains graphical components, the components ____.
62. How do you specify what the program should do when the user clicks a button?
a) Specify the actions to take in a class that implements the ButtonListener interface.
b) Specify the actions to take in a class that implements the ButtonEvent interface .
c) Specify the actions to take in a class that implements the ActionListener interface.
d) Specify the actions to take in a class that implements the EventListener interface.
Answer: c
63. A(n) ____ has an instance method addActionListener() for specifying which object is responsible for implementing
the action associated with the object.
a) JFrame
b) JSlider
c) JButton
d) JLabel
Answer: c
Maha Otaibi 11
65. Consider the following code snippet:
public static void main(String[] args)
{
final Order myOrder = new Order();
JButton button = new JButton("Calculate");
final JLabel label = new JLabel("Total amount due");
. . .
class MyListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
. . .
}
}
}
Which of the local variables can be accessed within the actionPerformed method?
a) Only button can be accessed..
b) All of the local variables can be accessed.
c) label and myOrder can be accessed.
d) Only myOrder can be accessed.
Answer: c
66. Consider the following code snippet which is supposed to show the total order amount when the button is clicked:
public static void main(String[] args)
{
final Order myOrder = new Order();
JButton button = new JButton("Calculate");
final JLabel label = new JLabel("Total amount due");
. . .
class MyListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
label.setText("Total amount due " + myOrder.getAmountDue());
}
}
ActionListener listener = new MyListener();
}
What is wrong with this code?
67. Use the ____ method to specify the height and width of a graphical component when you add it to a panel.
a) setPreferredDimensions.
b) setInitialDimensions.
c) setPreferredSize.
d) setInitialSize.
Answer: c
68) Assuming that the ClickListener class implements the ActionListener interface, what statement should be used to
complete the following code segment?
a) myPanel.addActionListener(listener);
b) myButton.addActionListener(listener);
c) myPanel.addActionListener(myButton);
d) myButton.addActionListener(ClickListener);
Answer: b
Maha Otaibi 12
69) Assume that the TimerListener class implements the ActionListener interface. If the actionPerformed
method in TimerListener needs to be executed every second, what statement should be used to complete the following code
segment?
a) java.awt.
b) javax.awt.
c) java.swing.
d) javax.swing.
Answer: d
71. When you use a timer, you need to define a class that implements the ____ interface.
a) TimerListener
b) TimerActionListener
c) ActionListener
d) StartTimerListener
Answer: c
72. The ____ class in the javax.swing package generates a sequence of events, spaced apart at even time intervals.
a) TimeClock
b) Timer
c) Clock
d) StopWatch
Answer: b
public RectangleComponent()
{
// The rectangle that the paint method draws
box = new Rectangle(BOX_X, BOX_Y,
Maha Otaibi 13
BOX_WIDTH, BOX_HEIGHT);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.draw(box);
}
public void moveTo(int x, int y)
{
box.setLocation(x, y);
repaint();
}
}
Which statement causes the rectangle to appear at an updated location?
a) repaint();
b) g2.draw(box);
c) box.setLocation(x, y);
d) private Rectangle box;
Answer: a
77. The ____ method should be called whenever you modify the shapes that the paintComponent method draws.
a) draw
b) paint
c) paintComponent
d) repaint
Answer: d
78. If the user presses and releases a mouse button in quick succession, which methods of the MouseListener interface are
called?
a) mousePressed, mouseReleased, and mouseClicked.
b) mousePressed, mouseReleased, and mouseDblClicked
c) Only the mouseClicked method.
d) Only the mouseDblClicked method.
Answer: b
79. Suppose listener is an instance of a class that implements the MouseListener interface. How many methods does
listener have?
a) 0 b) 1
c) 3 d) at least 5
Answer: d
Maha Otaibi 14
80. Use the ____ method to add a mouse listener to a component.
a) addListener
b) addMouseListener
c) addActionListener
d) addMouseActionListener
Answer: b
82. You wish to detect when the mouse is moved into a graphical component. Which methods of the MouseListener interface
will provide this information?
a) mouseMoved
b) mouseEntered
c) mouseOver
d) mouseIncoming
Answer: b
a) x = event.getXposition(); y = event.getYposition();
b) x = (MouseEvent) getX(); y = (MouseEvent) getY();
c) x = event.printX(); y = event.printY();
d) x = event.getX(); y = event.getY();
Answer: d
a) MouseAdapter class implements all of the methods of the MouseListener interface as do nothing methods, eliminating
the need to implement the MouseListener interface.
b) MouseAdapter class allows your program to accept input from multiple mice.
c) MouseAdapter class implements all of the methods of the ActionListener interface as do nothing methods, eliminating
the need to implement the ActionListener interface.
d) A class can implement the MouseAdapter class to handle mouse events.
Answer: a
Maha Otaibi 15
Chapter 10: Inheritance
1. A class that represents the most general entity in an inheritance hierarchy is called a/an ____.
a) Default class. b) Superclass.
c) Subclass. d) Inheritance class.
Answer: b
2. A class that represents a more specific entity in an inheritance hierarchy is called a/an ____.
a) Default class b) Superclass
c) Subclass. d) Inheritance class.
Answer: c
3. You are creating a class inheritance hierarchy about motor vehicles that will contain classes named Vehicle, Auto, and
Motorcycle. Which of the following statements is correct?
a) Vehicle should be the default class, while Auto and Motorcycle should be the subclasses.
b) Vehicle should be the superclass, while Auto and Motorcycle should be the subclasses.
c) Vehicle should be the subclass, while Auto and Motorcycle should be the superclasses.
d) Vehicle should be the subclass, while Auto and Motorcycle should be the default classes.
Answer: b
5. Insert the missing code in the following code fragment. This fragment is intended to call the Vehicle class's method.
public class Vehicle
{
. . .
public void setVehicleClass(double numberAxles)
{
. . .
}
}
public class Motorcycle extends Vehicle
{
. . .
public Motorcycle()
{
_______________;
}
}
a) Motorcyle.setVehicleClass(2.0);
b) Vehicle.setVehicleClass(2.0);
c) this;setVehicleClass(2.0);
d) setVehicleClass(2.0);
Answer: d
6. Insert the missing code in the following code fragment. This fragment is intended to call the Vessel class's method.
public class Vessel
{
. . .
public void set VesselClass(double vesselLength)
{
. . .
}
}
public class SpeedBoat extends Vessel
{
. . .
public SpeedBoat()
{
_______________;
}}
a) SpeedBoat.vesselLength(26.0);
b) Vessel.vesselLength(26.0);
c) this;vesselLength(26.0);
d) vesselLength(26.0);
Answer: d
Maha Otaibi 16
7. Consider the following inheritance hierarchy diagram:
!
Which of the following statements is correct?
!
Which of the following statements is correct?
a) Auto class inherits from LandVehicle class, and LandVehicle class inherits from Vehicle class.
b) Auto class inherits from LandVehicle class, and Vehicle class inherits from LandVehicle class.
c) LandVehicle class inherits from Auto class, and LandVehicle class inherits from Vehicle class.
d) LandVehicle class inherits from Auto class, and Vehicle class inherits from LandVehicle class.
Answer: a
Which represent valid class headers that would be found in this hierarchy?
Maha Otaibi 17
10. Consider the hierarchy of classes shown below.
a) Object
b) Comedy
c) RealityShow
d) This class has no superclass
Answer: a
12. All hamsters are rodents and all rodents are mammals. What hierarchy best captures this information?
13. All rodents are mammals and all canines are mammals. No canines are rodents and no rodents are canines. What hierarchy
best captures this information?
Maha Otaibi 18
14. Consider the classes shown below:
a) Line 1 only
b) Line 2 only
c) Lines 1 and 2
d) Neither line will compile without error
Answer: c
Maha Otaibi 20
20. Suppose the class Message is partially defined as shown below
public class Message
{
private String value;
a) inherits
b) implements
c) interface
d) extends
Answer: d
22. You are creating a Motorcycle class which is supposed to inherit from the Vehicle class. Which of the following class
declaration statements will accomplish this?
23. You are creating a Motorcycle class which is supposed to be a subclass of the Vehicle class. Which of the following
class declaration statements will accomplish this?
Maha Otaibi 21
24. You are creating a Motorcycle class that is supposed to be a subclass of the Vehicle class. Which of the following class
declaration statements will accomplish this?
a) A subclass inherits methods from its superclass but not instance variables.
b) A subclass inherits instance variables from its superclass but not methods.
c) A subclass inherits methods and instance variables from its superclass.
d) A subclass does not inherit methods or instance variables from its superclass.
Answer: c
a) A subclass that inherits methods from its superclass may not override the methods.
b) A subclass that inherits instance variables from its superclass may not declare additional instance variables.
c) A subclass may inherit methods or instance variables from its superclass but not both.
d) A subclass may inherit methods and instance variables from its superclass, and may also implement its own methods and
declare its own instance variables.
Answer: d
28. Which of the following indicates that a class named Class1 is a subclass of a class named Class2?
29. Which of the following indicates that a class named ClassA class is a superclass of the ClassB class?
a) The subclass must simply use the name of the superclass instance variable.
b) The subclass must declare its own instance variable with the same name as the superclass instance variable.
c) The subclass must use a public method of the superclass (if it exists) to update the superclass's private instance variable.
d) The subclass must have its own public method to update the superclass's private instance variable.
Answer: c
31. Which of the following indicates that the Motorcycle class is a subclass of the Vehicle class?
Maha Otaibi 22
32. Consider the following code snippet:
public class Vehicle
{
private String manufacturer;
. . .
public void setVehicleClass(double numberAxles)
{
. . .
}
}
If a Motorcycle class is created as a subclass of the Vehicle class, which of the following statements is correct?
a) A Motorcycle object inherits and can directly use both the instance variable manufacturer and the method
setVehicleClass.
b) A Motorcycle object inherits and can directly use the instance variable manufacturer but not the method
setVehicleClass.
c) A Motorcycle object inherits but cannot directly use either the instance variable manufacturer or the method
setVehicleClass.
d) A Motorcycle object inherits and can directly use the method setVehicleClass but cannot directly use the instance
variable manufacturer.
Answer: d
a) A Speedboat object inherits and can directly use both the instance variable manufacturer and the method
setVesselClass.
b) A Speedboat object inherits and can directly use the instance variable manufacturer but not the method
setVesselClass.
c) A Speedboat object inherits but cannot directly use either the instance variable manufacturer or the method
setVesselClass.
d) A Speedboat object inherits and can directly use the method setVesselClass but cannot directly use the instance
variable manufacturer.
Answer: d
a) myAuto.displayInfo()
b) myAuto.super.displayInfo()
c) myAuto.super.super.displayInfo()
d) This cannot be done unless the Auto class overrides the displayInfo method.
Answer: a
Maha Otaibi 24
public class LandVehicle extends Vehicle
{
public LandVehicle(String type)
{
. . .
}
}
37. Which of the following statements about superclasses and subclasses is true?
a) this b) my
c) parent d) super
Answer: d
42. If a subclass defines the same method name and the same parameter types for a method that appears in its superclass, ____.
a) the subclass method overloads the superclass method.
b) the subclass method overrides the superclass method.
c) the subclass has implemented its superclass's method.
d) a compiler error will occur.
Answer: b
a) The Motorcycle class's setVehicleClass method overrides the Vehicle class's setVehicleClass method.
b) The Vehicle class's setVehicleClass method overrides the Motorcycle class's setVehicleClass method.
c) The Motorcycle class's setVehicleClass method overloads the Vehicle class's setVehicleClass method.
d) The Vehicle class's setVehicleClass method overloads the Motorcycle class's setVehicleClass method.
Answer: a
Maha Otaibi 26
44. Consider the following code snippet:
Maha Otaibi 27
public void setDepartment(String deptName)
{
. . .
}
}
Which of the following statements is NOT correct?
a) The Programmer class can call the setDepartment method of the Employee class.
b) The Employee class can call the setProjectName method. c) The Programmer class's setDepartment method
overrides the Employee class's setDepartment method.
d) The Programmer class can call the setDepartment method of the Programmer class.
Answer: b
Maha Otaibi 28
50. If a subclass contains a method with the same name as a method in its superclass, but with different parameter types, the
subclass method is said to ____ the method of the superclass.
a) implement
b) inherit
c) override
d) overload
Answer: d
51. If a subclass uses the same method name but different parameter types for a method that appears in its superclass, ____.
a) It invokes the constructor of the Vehicle class from within the constructor of the Auto class.
b) It invokes the constructor of the Auto class from within the constructor of the Vehicle class.
c) It invokes a private method of the Vehicle class from within a method of the Auto class.
d) This code will not compile.
Answer: a
a) It invokes the constructor of the Vehicle class from within the constructor of the Motorcycle class.
b) It invokes the constructor of the Motorcycle class from within the constructor of the Vehicle class.
c) It invokes a private method of the Vehicle class from within a method of the Motorcycle class.
d) This code will not compile.
Answer: a
Maha Otaibi 29
55. Consider the following code snippet:
a) The Motorcycle class constructor would invoke the constructor of the Vehicle class with no parameters.
b) The Vehicle class constructor would invoke the constructor of the Motorcycle class with no parameters.
c) The Motorcycle class constructor would invoke the constructor of the Vehicle class with a parameter value of 0.
d) This code would not compile.
Answer: a
Maha Otaibi 30
59. Consider the classes shown below:
public class Parent
{
public void doSomething() // method 1
{ /* Implementation not shown */ }
}
public class Child extends Parent
{
public void doSomething(int n) // method 2
{ /* Implementation not shown */ }
public void doSomething() // method 3
{ /* Implementation not shown */ }
}
If the variable kid is defined below, which version of the doSomething method can be called on the variable kid?
Child kid = new Child();
a) Methods 1 and 2 only
b) Method 2 only
c) Methods 2 and 3 only
d) Methods 1, 2, and 3
Answer: b
If the variable kid is defined below, which version of the doSomething method can be called on the variable kid?
a) Method 1 only
b) Methods 2 and 3 only
c) Methods 1 and 2 only
d) Methods 1, 2, and 3
Answer: a
a) 24 24
b) -7 -7
c) -7 24
d) 24 -7
Answer: c
a) -7 24
b) 24 24
c) -7 -7
d) 24 -7
Answer: a
A concrete subclass of Message, FrenchMessage, is defined. Which methods must FrenchMessage define?
a) translate() only
b) getMessage() only
c) The FrenchMessage constructor and translate() only
d) The FrenchMessage constructor, getMessage(), and translate()
Answer: a
Maha Otaibi 32
64. Consider the Counter class below.
public class Counter
{
public int count = 0;
Maha Otaibi 33
67. Consider the following class hierarchy:
public class Vehicle
{
private String type;
public Vehicle(String type)
{
this.type = type;
}
public String getType()
{
return type;
}
}
public class LandVehicle extends Vehicle
{
public LandVehicle(String type)
{
. . .
}
}
public class Auto extends LandVehicle
{
public Auto(String type)
{
. . .
}
}
Which of the following code fragments is NOT valid in Java?
a) Vehicle myAuto = new Auto("sedan");
b) LandVehicle myAuto = new Auto("sedan");
c) Auto myAuto = new Auto("sedan");
d) LandVehicle myAuto = new Vehicle("sedan");
Answer: d
If the Programmer class inherits from the Employee class, and both classes have an implementation of the
increaseSalary method with the same set of parameters and the same return type, which statement is correct?
Assume that the Auto class inherits from the Vehicle class, and both classes have an implementation of the moveForward
method with the same set of parameters and the same return type. Which class's moveForward method is to be executed is
determined by ____.
Assume that the Programmer class inherits from the Employee class, and both classes have an implementation of the
increaseSalary method with the same set of parameters and the same return type. Which class's increaseSalary
method is to be executed is determined by ____.
a) the hierarchy of the classes.
b) the variable's type.
c) the actual object type.
d) it is not possible to determine which method is executed.
Answer: c
a) You can create an object from a concrete class, but not from an abstract class.
b) You can create an object from an abstract class, but not from a concrete class.
c) You cannot have an object reference whose type is an abstract class.
d) You cannot create subclasses from abstract classes.
Answer: a
75. If a class has an abstract method, which of the following statements is NOT true?
You wish to create a concrete subclass named PolisherMachine. Which of the following is the correct way to declare this
subclass?
a)
public class PolisherMachine implements Machine
{
public void setRPMs() { . . . }
}
b)
public class PolisherMachine extends Machine
{
void setRPMs() { . . . }
Maha Otaibi 35
}
c)
public class PolisherMachine implements Machine
{
void setRPMs() { . . . }
}
d)
public class PolisherMachine extends Machine
{
public void setRPMs() { . . . }
}
Answer: d
c)
public class Programmer implements Employee
{
void setSalary() { . . . }
}
d)
public class Programmer extends Employee
{
public void setSalary() { . . . }
}
Answer: d
78. A class from which you cannot create objects is called a/an ____.
a) Abstract class.
b) Concrete class.
c) Non-inheritable class.
d) Superclass.
Answer: a
81. The ____ reserved word in a class definition ensures that subclasses cannot be created from this class.
a) abstract b) anonymous
c) final d) static
Answer: c
Maha Otaibi 36
82. The ____ reserved word in a method definition ensures that subclasses cannot override this method.
a) abstract b) anonymous
c) final d) static
Ans: c
86. To ensure that an instance variable can only be accessed by the class that declared it, the variable should be declared as ____.
a) public
b) private
c) protected
d) final
Answer: b
87. With a few exceptions, instance variables of classes should always have ___ access.
a) final
b) private
c) public
d) protected
Answer: b
Assume that the Programmer class inherits from the Employee class, and neither class has an implementation of the
toString() method. Which of the following statements is correct?
a) The toString() method of the Object class will be used when this code is executed.
b) The toString() method of the String class will be used when this code is executed.
c) This code will not compile because there is no toString() method in the Employee class.
d) This code will not compile because there is no toString() method in the Programmer class.
Answer: a
Maha Otaibi 37
90. Consider the following code snippet:
int numAxles = 4;
String s = "Number of axles is " + numAxles;
Assume that the Auto class has not implemented its own toString() method. What value will s contain when this code is
executed? a) s will contain the values of the instance variables in consumerAuto.
b) s will contain only the class name of the consumerAuto object.
c) s will contain the class name of the consumerAuto object followed by a hash code.
d) This code will not compile.
Answer: c
Assume that the Employee class has not implemented its own toString() method. What value will s contain when this code
is executed?
a) s will contain the values of the instance variables in programmer.
b) s will contain only the class name of the programmer object.
c) s will contain the class name of the programmer object followed by a hash code.
d) This code will not compile.
Answer: c
Maha Otaibi 38
{
. . .
}
. . .
}
What is wrong with this code?
a) A class cannot override the equals() method of the Object class.
b) The equals() method must be declared as private.
c) A class cannot change the parameters of a superclass method when overriding it.
d) There is nothing wrong with this code.
Answer: c
Maha Otaibi 39
a) This code tests whether anObject was created from a superclass of Auto.
b) This code creates a subclass type object from a superclass type object.
c) This class safely converts an object of any type to an object of type Auto.
d) This code safely converts an object of type Auto or a subclass of Auto to an object of type Auto.
Answer: d
2) Which of the following questions should you ask yourself in order to determine if you have named your class properly?
a) Does the class name contain 8 or fewer characters?
b) Is the class name a verb?
c) Can I visualize an object of the class?
d) Does the class name describe the tasks that this class will accomplish?
Answer: c
3) Which of the following would be an appropriate name for a game-related class?
a) FinalizeLevelOne
b) InitialLevel
c) ResetTheCurrentLevel
d) AscendToFinalLevel
Answer: b
4) Which of the following would be an appropriate name for a class used in an inventory application?
a) Product
b) InitializeInventoryLevel
c) ResetCurrentInventoryLevel
d) ReceiveNewProducts
Answer: a
5) You are designing an application to support an automobile rental agency. Which of the following probably should NOT be
represented as an object?
a) Auto
b) Customer
c) Payment amount
d) Rental contract
Answer: c
6) You are designing an application to support a veterinary clinic. Which of the following probably should NOT be represented as
an object?
a) Pet
b) Customer
c) Medical service performed
d) Drug dosage
Answer: d
a) Association b) Aggregation
c) Dependency d) Class
Answer: d
Maha Otaibi 40
9) After you have identified a set of classes needed for a program, you should now ____.
a) Define the behavior of each class.
b) Look for nouns that describe the tasks.
c) Begin writing the code for the classes.
d) Establish the relationships between the classes.
Answer: a
11) When using the CRC method, other classes that are needed to fulfill the responsibilities of a given class are called its ____.
a) Related classes. b) Responsible classes.
c) Collaborators. d) Concurrent classes.
Answer: c
12) When using the CRC method, if you determine that a class cannot carry out a particular task by itself and needs the help of
another class to complete the task, you should ____.
a) Do nothing on this class’s CRC card. The task will be shown on the other class’s CRC card.
b) Add this class onto the other class’s CRC card as a collaborator.
c) Add the other class onto this class’s CRC card as a collaborator.
d) Add each class onto the other class's CRC card as a collaborator.
Answer: c
13) Which of the following is the most important consideration when designing a class?
a) Each class should represent an appropriate mathematical concept.
b) Each class should represent a single concept or object from the problem domain.
c) Each class should represent no more than three specific concepts.
d) Each class should represent multiple concepts only if they are closely related.
Answer: b
14) Under which of the following conditions would the public interface of a class be considered cohesive?
a) All of its features are public and none of its features are static.
b) The quality of the public interface is rated as moderate to high.
c) All of its features are related to the concept that the class represents.
d) It is obvious that the public interface refers to multiple concepts.
Answer: c
15) A class (ClassOne) is considered to have a dependency on another class (ClassTwo) under which of the following
conditions?
a) Each class uses objects of the other.
b) The public interfaces of both classes are cohesive.
c) ClassTwo uses objects of ClassOne.
d) ClassOne uses objects of ClassTwo.
Answer: d
16) A UML class diagram would be most useful in visually illustrating which of the following?
a) the cohesiveness of a class’s interface.
b) the amount of complexity of a class’s interface.
c) dependencies between classes.
d) relationships between classes and their interfaces.
Answer: c
17) Why is it generally considered good practice to minimize coupling between classes?
a) Low coupling increases the operational efficiency of a program.
b) High coupling implies less interface cohesion.
c) High coupling increases program maintenance and hinders code reuse.
d) Low coupling decreases the probability of code redundancy.
Answer: c
20) If many classes of a program depend on each other, we say that ____.
a) is-a
b) has-a
c) depends-on
d) knows-about
Answer: d
23) Which statement correctly describes the class relationship shown in this diagram?
24) Which of the following code snippets denotes that the Purse class depends on the Wallet class?
a)
public class Purse extends Wallet
b)
public class Wallet extends Purse
c)
public class Wallet
{
private Purse aPurse;
}
d)
public class Purse
{
private Wallet aWallet;
}
Answer: d
Maha Otaibi 42
25) Which of the following code snippets denotes that the Pen class depends on the Ink class?
a)
public class Pen extends Ink
b)
public class Ink extends Pen
c)
public class Pen
{
private Ink anInk;
}
d)
public class Ink
{
private Pen aPen;
}
Answer: c
26) Which of the following code snippets denotes that the Kitchen class depends on the Stove class?
a)
public class Kitchen extends Stove
b)
public class Stove
{
private Kitchen[] kitchens;
}
c)
public class Kitchen
{
private Stove aStove;
}
d)
public class Kitchen implements Stove
Answer: c
a) Inheritance. b) Aggregation.
c) Polymorphism. d) Dependency.
Answer: b
a) Inheritance. b) Aggregation.
c) Polymorphism. d) Association.
Answer: b
34) A CashRegister class contains an array list of Coin objects. This is best described as an example of ____.
a) Association
b) Inheritance
c) Cohesiveness
d) Aggregation
Answer: d
35) A Quiz class contains an array of Question objects. This is best described as an example of ____.
a) Aggregation
b) Cohesiveness
c) Association
d) Inheritance
Answer: a
37) In general, you need ____ when an object needs to remember another object between method calls.
a) inheritance
b) aggregation
c) association
d) an interface implementation
Answer: b
Maha Otaibi 44
38) Which statement correctly describes the class relationship shown in this diagram?
39) Which of the following code snippets denotes that the Fleet class aggregates the Taxi class?
a)
public class Fleet extends Taxi
b)
public class Taxi extends Fleet
c)
public class Fleet
{
private ArrayList<Taxi> taxicabs;
}
d)
public class Taxi
{
private Fleet myFleet;
}
Answer: c
40) Which of the following code snippets denotes that the Kitchen class aggregates the Dish class?
a)
public class Kitchen extends Dish
b)
public class Dish extends Kitchen
c)
public class Kitchen
{
private Dish[] dishes;
}
d)
public class Dish
{
private Kitchen myKitchen;
}
Answer: c
a) Inheritance. b) Aggregation.
c) Polymorphism. d) Dependency.
Answer: a
Maha Otaibi 45
43) Consider the following code snippet:
Which of the following statements correctly describes the relationship between the Motorcycle and Vehicle classes?
}
Which of the following statements is NOT correct?
a) SailBoat inherits from Vessel.
b) Sail depends on Sailboat.
c) Sailboat aggregates Engine.
d) SailBoat aggregates Sail.
Answer: b
Maha Otaibi 46
48) Consider the following code snippet:
public class Manager extends Employee
{
private Project[] projects;
private Address address;
. . .
}
Which of the following statements is NOT correct?
51) Which of the following code snippets denotes that the Lime class inherits from the Citrus class?
a)
public class Lime extends Citrus
b)
public class Citrus extends Lime
c)
public class Lime
{
private ArrayList<Citrus> fruits;
}
d)
public class Citrus
{
private ArrayList<Lime> limes;
}
Answer: a
52) Which of the following code snippets denotes that the Rose class inherits from the Flower class?
a)
public class Flower extends Rose
b)
public class Rose extends Flower
c)
public class Rose
{
private Flower[] flowers;
}
d)
public class Flower
{
private Rose[] limes;
}
Answer: b
53) When designing classes, if you find classes with common behavior you should ____.
a) Combine them all into a single class.
b) Place the common behavior into a superclass.
c) Place the common behavior into a subclass.
d) Give them similar names.
Answer: b
Maha Otaibi 47
54) In a UML diagram, an interface implementation is denoted by ____.
a) A dotted line with a closed arrow tip.
b) A solid line with a closed arrow tip.
c) A dotted line with an open arrow tip.
d) A solid line with an open arrow tip.
Answer: a
55) In a UML diagram, the relationship symbol shown below denotes ____.
!
a) inheritance b) aggregation
c) dependency d) interface implementation
Answer: b
56) In a UML diagram, the relationship symbol shown below denotes ____.
!
a) inheritance b) aggregation
c) dependency d) interface implementation
Answer: d
57) In a UML diagram, the relationship symbol shown below denotes ____.
!
a) inheritance b) aggregation
c) dependency d) interface implementation
Answer: a
58) Which statement correctly describes the class relationship shown in this diagram?
59) Which statement correctly describes the class relationship shown in this diagram?
!
a) Tire class aggregates Car class.
b) Car class aggregates Tire class.
c) Car class inherits from Tire class.
d) Tire class inherits from Car class.
Answer: b
Maha Otaibi 48
60) You have determined a need for a Book class and a Page class in your program. Which relationship is most appropriate
between these classes?
a) Inheritance
b) Aggregation
c) Dependency
d) Interface implementation
Answer: b
61) You have determined a need for an Employee class and a TemporaryEmployee class in your program. Which
relationship is most appropriate between these classes?
a) Inheritance
b) Aggregation
c) Dependency
d) Interface implementation
Answer: a
62) ____ relationships come from the collaboration columns on the CRC cards.
a) Association
b) Inheritance
c) Dependency
d) Attribute
Answer: c
63) When using CRC cards, UML diagrams should be created ___.
a) Prior to discovering classes.
b) After you have discovered classes and their relationships.
c) During the implementation phase.
d) To produce final documentation of the system.
Answer: b
65) How does a UML diagram denote classes and their attributes and methods?
a) A class rectangle contains the class name in the top, methods in the middle, and attributes in the bottom.
b) A class rectangle contains the class name in the top, attributes in the middle, and methods in the bottom.
c) A class rectangle contains the methods in the top, class name in the middle, and attributes in the bottom.
d) A class rectangle contains the attributes in the top, methods in the middle, and class name in the bottom.
Answer: b
66) How does a UML diagram denote a multiplicity of one or more in an aggregation relationship?
a) *
b) 1..*
c) *..1
d) 1..n
Answer: b
!
What does this diagram indicate about the relationship between the customers and bank accounts?
a) A bank account may be owned by only one customer.
b) A bank account may be owned by one or more customers.
c) A customer may have only one bank account.
d) A customer may have one or more bank accounts.
Answer: d
68) Which of the following statements about associations between classes is true?
a) A class is associated with another class if both classes are in the same package.
b) A class is associated with another class if the class inherits from the other class.
c) A class is associated with another class if the other class inherits from this class.
d) A class is associated with another class if you can navigate from objects of one class to objects of the other class.
Answer: d
Maha Otaibi 49
69) You have determined the need for a File class and a Folder class in your program. Which of the following would best
describe the relationship between these classes?
a) Aggregation
b) Association
c) Composition
d) Inheritance
Answer: c
70) If you have parallel arrays or array lists of the same length which each store a part of what could be considered an object,
____.
a) You should rewrite the program to use a two-dimensional array.
b) You should rewrite the program to use a two-dimensional array list.
c) You should create a class to hold the related data in the ith slice of each array, and then create an arraylist of objects.
d) There are no alternatives to this type of program design.
Answer: c
71) Parallel arrays are ____.
a) Two or more arrays or array lists of the same length which each store a part of what could be considered an object.
b) Two or more arrays or array lists of the same length.
c) Two or more arrays or array lists of the same data type.
d) Two or more arrays or array lists that are declared one after the other in a program.
Answer: a
73) Select a code segment to complete the Name class, so that it reflects a dependency relationship between Name and String.
d)
{
private ArrayList<String> names;
…
}
Answer: b
74) Select a code segment to complete the Team class, so that it reflects an aggregation relationship between Team and Player.
public class Team ___________________________
a)
extends Player
{
…
}
b)
{
private Player aPlayer;
…
Maha Otaibi 50
}
c)
implements Player
{
…
}
d)
{
private ArrayList<Player> players;
…
}
Answer: d
75) Select a code segment to complete the Player class, so that it reflects an inheritance relationship between Player and
Person.
public class Player ___________________________
a)
extends Person
{
…
}
b)
{
private Person thePlayer;
…
}
c)
implements Person
{
…
}
d)
{
private ArrayList<Person> players;
…
}
Answer: a
76) Select a code segment to complete the SmartPhone class, so that it reflects an interface implementation relationship
between SmartPhone and MP3Player.
public class SmartPhone ___________________________
a)
extends MP3Player
{
…
}
b)
{
private MP3Player musicPlayer;
…
}
c)
implements MP3Player
{
…
}
d)
implements interface MP3Player
{
…
}
Answer: c
77) The textbook recommends a five-part program development process consisting of the following activities:
I Use UML diagrams to record class relationships.
II Gather requirements.
III Implement the program.
IV Use CRC cards to identify classes.
V Use javadoc to document method behavior.
Maha Otaibi 51
Which is the correct order in which these activities should be completed?
a) IV, II, I, III, V
b) IV, II, I, V, III
c) II, IV, I, III, V
d) II, IV, I, V, III
Answer: d
79) You are designing a software solution for an automobile rental company. You have decided that the following nouns apply to
the requirements: Auto, Customer, Address, Rental Contract, Mileage, Rental Date, Daily Rate, Total. Which of these should be
represented as classes?
a) All of them.
b) Auto, Customer, Address, Rental Contract.
c) Auto, Customer, Address, Rental Contract, Mileage.
d) Auto, Customer, Address, Rental Contract, Mileage, Rental Date, Daily Rate.
Answer: b
80) You are designing a software solution for an automobile rental company. You have decided that the following nouns apply to
the requirements: Auto, Customer, Address, Rental Contract, Mileage, Rental Date, Daily Rate, Total. Which of these should be
represented as instance variables?
a) Mileage
b) Mileage, Daily Rate.
c) Mileage, Rental Date, Daily Rate.
d) Mileage, Rental Date, Daily Rate, Total.
Answer: c
81) You are designing a software solution for a veterinary clinic. The clinic provides various services for each pet on each visit.
You have decided that the following nouns apply to the requirements: Customer, Address, Pet, Visit, Visit Date, Service Charge,
Total Charge, Next Appointment. Which of these should be represented as classes?
a) All of them.
b) Customer, Address, Pet, Visit.
c) Customer, Address, Pet, Visit, Service Charge.
d) Customer, Address, Pet, Visit, Service Charge, Total Charge, Visit Date, Next Appointment.
Answer: b
82) You are designing a software solution for a veterinary clinic. The clinic provides various services for each pet on each visit.
You have decided that the following nouns apply to the requirements: Customer, Address, Pet, Visit, Visit Date, Service Charge,
Total Charge, Next Appointment. Which of these should be represented as instance variables?
a) Service Charge
b) Service Charge, Visit Date.
c) Service Charge, Visit Date, Next Appointment.
d) Service Charge, Visit Date, Next Appointment, Total Charge.
Answer: c
83) You are designing a software solution for an automobile rental company. A customer may rent only a single auto at a given
time. You have decided that the following classes are needed: Auto, Customer, Address, Rental Contract. Which of these should be
represented as aggregation?
84) You are designing a software solution for a veterinary clinic. The clinic provides various services for each pet on each visit.
You have decided that the following classes are needed: Customer, Address, Pet, and Visit. Which of these should be represented
as aggregation?
Maha Otaibi 52
85) Given the following diagram showing class relationships:
!
What type of relationship is shown between Invoice and LineItem?
a) LineItem inherits from Invoice.
b) LineItem aggregates Invoice.
c) Invoice aggregates LineItem.
d) Invoice inherits from LineItem.
Answer: c
!
What type of relationship is shown between Invoice and Product?
a) Product inherits from Invoice.
b) Product aggregates Invoice.
c) Invoice inherits from Product.
d) Invoice is dependent on Product.
Answer: d
!
What type of relationship is shown between LineItem and Product?
a) Product inherits from LineItem.
b) Product aggregates LineItem.
c) LineItem aggregates Product.
d) LineItem inherits from Product.
Answer: c
!
What type of relationship is shown between Invoice and Address?
a) Address inherits from Invoice.
b) Invoice aggregates Address.
c) Address aggregates Invoice.
d) Invoice inherits from Address.
Answer: b
Maha Otaibi 53
89) The final step of the design phase recommended by the textbook is to ____.
90) When documenting discovered classes and methods during the design phase, you should ____.
a) Create a Java source file for each class, write the method signatures, and use javadoc comments to describe the methods, but
leave the method bodies blank.
b) Create a Java source file for each class and write code to implement all of its methods, and use javadoc comments to document
them.
c) Create a Java source file for each class, use javadoc comments to document the methods that are to be added later, but do not
write any code for the methods.
d) Documentation of methods should not be done during the design phase.
Answer: a
91) Which of the following can be used to record the behavior of classes?
a) Javadoc comments
b) Nouns and verbs in the problem description
c) Polymorphism
d) UML notation
Answer: a
92) During the implementation phase, which of the following statements is true?
93) During the implementation phase, which of the following statements is true?
94) During the implementation phase, which of the following statements is true?
95) When using UML to create state diagrams, a state is denoted by ____.
96) When using UML to create state diagrams, state change is denoted by ____.
Maha Otaibi 54
97) Given the following diagram showing class relationships:
What of the following best describes the type of relationship shown between Bank and Customer?
a) Customer aggregates Bank, indicating that a customer may deal with many banks.
b) Bank aggregates Customer, indicating that a bank may deal with many customers.
c) Bank depends on Customer, indicating that a bank may deal with many customers.
d) Customer depends on Bank, indicating that a customer may deal with many banks.
Answer: b
99) Suppose that the invoice-printing application from section 12.3 needs to be enhanced by including the computation and
printing of sales taxes as needed. Since some vendors charge no sales taxes, the original Invoice class needs to be preserved.
Select the code segment that best illustrates reuse of the existing Invoice class.
public class TaxableInvoice ___________________________
a)
extends Invoice
{
…
}
b)
{
private Invoice originalInvoice;
…
}
c)
implements Invoice
{
…
}
d)
{
private ArrayList<Invoice> invoices;
…
}
Answer: a
Maha Otaibi 55
100) Regarding the invoice-printing application from section 12.3, it is decided that a Customer class is needed to store
customer information, including the name, billing address, and a customer id number to be printed at the top of each invoice.
Since the existing Address class already stores the customer’s name and physical address, the new Customer class can simply
reuse Address. Select the code segment that best illustrates how the Customer class can reuse the existing Address class.
public class Customer ___________________________
a)
extends Address
{
private String idNumber;
…
}
b)
{
private Address information;
private String idNumber;
…
}
c)
implements Address
{
private String idNumber;
…
}
d)
{
private Address information;
private String name;
private String street;
private String city;
private String state;
private String zip;
private String idNumber;
…
}
Answer: b
101) Suppose that the invoice-printing application from section 12.3 needs to be enhanced by making it possible for class
InvoicePrinter to store several invoices to be printed. Select the code segment that best illustrates reuse of the existing
Invoice class for this purpose.
public class InvoicePrinter ___________________________
a)
extends Invoice
{
…
}
b)
{
public static void main(String[] args)
{
Invoice invoice1;
Invoice invoice2;
…
}
c)
implements Invoice
{
…
}
d)
{
public static void main(String[] args)
{
ArrayList<Invoice> invoices;
…
}
}
Answer: d
Maha Otaibi 56
102) Suppose you are developing a payroll application that computes and displays weekly paycheck amounts for various
employees. As a result of the design phase, the partial Employee class below is developed. Select the method header that best
completes the class, according to the method comments.
public class Employee
{
private int hoursWorked;
/**
Computes the weekly salary for this employee.
@param hourlyRate the rate per hour earned by the employee
@return the weekly salary
*/
_________________________________________
{
// method body
}
}
a) public void computeSalary(double hourlyRate)
b) public double computeSalary(double hourlyRate, int hoursWorked)
c) public double computeSalary(double hourlyRate)
d) public double computeSalary(int hoursWorked)
Answer: c
103) Suppose you are developing a payroll application that computes and displays weekly paycheck amounts for various
employees. As a result of the design phase, an Employee class is developed. In addition, the Payroll class is designed to
store and process information for various employees. Select the code segment that best completes the Payroll class.
a)
extends Employee
{
…
}
b)
{
public static void main(String[] args)
{
Employee anEmployee;
…
}
c)
{
public static void main(String[] args)
{
int hoursWorked;
double hourlyRate;
…
}
}
d)
{
public static void main(String[] args)
{
ArrayList<Employee> employees;
…
}
}
Answer: d
104) Suppose you are developing a payroll application that computes and displays weekly paycheck amounts for various
employees. As a result of the design phase, the partial Employee class below is developed. Select the method header that best
completes the class, according to the method comments.
public class Employee
{
private double hourlyRate;
private int hoursWorked;
/**
Modifies the hourly rate for this employee.
@param newHourlyRate the rate per hour earned by the employee
*/
_________________________________________
{
// method body
Maha Otaibi 57
}
}
a) public void changeRate(double newHourlyRate)
b) public void changeRate(double newHourlyRate, int hoursWorked)
c) public double changeRate(double newHourlyRate)
d) public double changeRate(double newHourlyRate, int hoursWorked)
Answer: a
Maha Otaibi 58
Triangle smallerTriangle = new Triangle(width);
int fib(int n)
{
// assumes n >= 0
if (n <= 1)
{
return n;
}
else
{
return (fib(n - 1) + fib(n - 2));
}
}
a) n < 1
b) n <= 1
c) fib(n – 1)
d) fib(n - 1) + fib(n – 1)
Answer: b
a) n <= 0
b) n == 1
c) n <= 0 or n == 1
d) n > 0
Answer: c
Maha Otaibi 60
11) Consider the following recursive code snippet:
a) 3
b) 6
c) 18
d) 729
Answer: c
a) 821
b) 128
c) 12
d) 10
Answer: b
Maha Otaibi 61
14) Consider the recursive method myPrint shown in this code snippet:
public void myPrint(int n)
{
if (n < 10)
{
System.out.print(n);
}
else
{
int m = n % 10;
System.out.print(m);
myPrint(n / 10);
}
}
What does this method do?
a) Prints a positive int value forward, digit by digit.
b) Prints a positive int value backward, digit by digit.
c) Divides the int by 10 and prints out its last digit.
d) Divides the int by 10 and prints out the result.
Answer: b
15) Complete the code for the recursive method printSum shown in this code snippet, which is intended to return the sum of
digits from 1 to n:
public static int printSum(int n)
{
if (n == 0)
{
return 0;
}
else
{
______________________________
}
}
a) return (printSum(n - 1));
b) return (n + printSum(n + 1));
c) return (n + printSum(n - 1));
d) return (n - printSum(n - 1));
Answer: c
16) Consider the code for the recursive method mysteryPrint shown in this code snippet:
public static int mysteryPrint(int n)
{
if (n == 0)
{
return 0;
}
else
{
return (n + mysteryPrint(n-1));
}
}
What will be printed with a call to mysteryPrint(-4)?
a) 0 b) -10
c) -22 d) Nothing – a StackoverflowError exception will occur
Answer: d
17) Consider the code for the recursive method myPrint shown in this code snippet:
public static int myPrint(int n)
{
if (n == 0)
{
return 0;
{
else
{
return (n + myPrint(n - 1));
}
Maha Otaibi 62
}
To avoid infinite recursion, which of the following lines of code should replace the current terminating case?
a) if (n == -1) b) if (n <= 0)
c) if (n >= 0) d) The terminating case as shown will avoid infinite recursion.
Answer: b
18) Consider the getArea method from the textbook shown below:
public int getArea()
{
if (width <= 0) { return 0; } // line #1
if (width == 1) { return 1; } // line #2
Triangle smallerTriangle = new Triangle(width – 1); // line #3
int smallerArea = smallerTriangle.getArea(); // line #4
return smallerArea + width; // line #5
}
Which line has the recursive case?
a) line #1
b) line #2
c) line #3
d) line #4
Answer: d
Maha Otaibi 63
21) Insert the missing code in the following code fragment. This fragment is intended to recursively compute xn, where x and n
are both non-negative integers:
public int power(int x, int n)
{
if (n == 0)
{
____________________
}
else
{
return x * power(x, n - 1);
}
}
a) return 1;
b) return x;
c) return power(x, n - 1);
d) return x * power(x, n - 1);
Answer: a
22) If recursion does not have a special terminating case, what error will occur?
a) Index out of range
b) Illegal argument
c) Stack overflow
d) Out of memory
Answer: c
25) ____ recursion can occur when a recursive algorithm does not contain a special case to handle the simplest computations
directly.
a) Mutual
b) Non-mutual
c) Terminating condition
d) Infinite
Answer: d
26) If a recursive method does not simplify the computation within the method and the base case is not called, what will be the
result?
a) The terminating condition will be executed and recursion will end.
b) The recursion calculation will occur correctly regardless.
c) This cannot be determined.
d) Infinite recursion will occur.
Answer: d
Maha Otaibi 64
27) Consider the getArea method from the textbook shown below:
public int getArea()
{
if (width <= 0) { return 0; } // line #1
Triangle smallerTriangle = new Triangle(width – 1); // line #2
int smallerArea = smallerTriangle.getArea(); // line #3
return smallerArea + width; // line #4
}
If line#1 was removed, what would be the result?
a) The recursive method would cause an exception for values below 0.
b) The recursive method would construct triangles whose width was negative.
c) The recursive method would terminate when the width reached 0.
d) The recursive method would correctly calculate the area of the original triangle.
Answer: b
28) When a recursive method is called, and it does not perform recursion, what must be true?
a) The terminating condition was true.
b) One recursive case condition was true.
c) All recursive case conditions were true.
d) An exception will occur in the method.
Answer: a
29) Consider the getArea method from the textbook shown below.
public int getArea()
{
if (width <= 0) { return 0; } // line #1
if (width == 1) { return 1; } // line #2
Triangle smallerTriangle = new Triangle(width – 1); // line #3
int smallerArea = smallerTriangle.getArea(); // line #4
return smallerArea + width; // line #5
}
Assume that line #2 is changed to this:
if (width == 1) { return 2; }
How would this affect calls to getArea?
a) It would add 1 to all calls except those where width <= 0.
b) It would make no difference to any call.
c) It would double every triangle area.
d) It would subtract 1 from all calls.
Answer: a
30) Consider the getArea method from the textbook shown below:
public int getArea()
{
if (width <= 0) { return 0; } // line #1
if (width == 1) { return 1; } // line #2
Triangle smallerTriangle = new Triangle(width – 1); // line #3
int smallerArea = smallerTriangle.getArea(); // line #4
return smallerArea + width; // line #5
}
Assume that line #3 is changed to this:
Triangle smallerTriangle = new Triangle(width);
This would cause infinite recursion for ____.
a) triangles with width equal to 0 b) triangles with width equal to 1
c) triangles with width greater than or equal to 2 d) triangles of any width
Answer: c
31) Consider the getArea method from the textbook shown below:
public int getArea()
{
if (width <= 0) { return 0; } // line #1
if (width == 1) { return 1; } // line #2
Triangle smallerTriangle = new Triangle(width – 1); // line #3
int smallerArea = smallerTriangle.getArea(); // line #4
return smallerArea + width; // line #5
}
Assume line #3 is changed to this:
Triangle smallerTriangle = new Triangle(width + 1)
When calling the getArea method on a Triangle object with width = 4, what result will be produced?
a) area for all triangles will be computed to be too high
b) area for all triangles will be computed to be too low
Maha Otaibi 65
c) area will only be incorrect for a triangle objects with width = 1
d) infinite recursion will occur for triangle objects with width >= 2
Answer: d
32) Consider the getArea method from the textbook shown below:
public int getArea()
{
if (width <= 0) { return 0; } // line #1
if (width == 1) { return 1; } // line #2
Triangle smallerTriangle = new Triangle(width – 1); // line #3
int smallerArea = smallerTriangle.getArea(); // line #4
return smallerArea + width; // line #5
}
If line #1 was eliminated from the method, what would be the result when calling getArea?
a) A negative or zero width would cause problems.
b) Nothing - the method would still work correctly.
c) We would lose our only recursive case.
d) A positive width would reduce the correct area by 1.
Answer: a
33) How many recursive calls to the fib method shown below would be made from an original call to fib(4)? (Do not count
the original call)
public int fib(int n)
{ // assumes n >= 0
if (n <= 1)
{
return n
}
else
{
return (fib(n - 1) + fib(n - 2));
}
}
a) 1 b) 2
c) 4 d) 8
Answer: d
34) Would switching the special case order affect the return value of the following method?
35) Which of the following options could be used as a terminating condition for a recursive method that finds the middle character
of a String with any number of characters?
I the length of the String is 1
II first and last String characters match
III the String is not empty
a) I
b) II
c) I, II and III
d) I and III
Answer: a
Maha Otaibi 66
36) Consider the problem of arranging matchsticks so as to form a row of rectangles, as shown below.
_ _ _ _ _ _
|_ _|_ _|_ _|
Complete the recursive method below, which is designed to return the number of matchsticks needed to form n rectangles.
public static int matchsticks(int rectangles)
{
if (rectangles == 1) // 1 square can be formed with 6 matchsticks
{
return 6;
}
else
{
return ___________________________
}
}
a) 6 + matchsticks(rectangles – 1);
b) 5 + matchsticks(rectangles – 1);
c) 6 * rectangles;
d) matchsticks(rectangles + 6);
Answer: b
37) Consider the method below, which implements the exponentiation operation recursively. Select the statement that should be
used to complete the method, so that it handles the special case correctly.
38) Consider the method below, which displays the characters from a String in reverse order. Each character appears on a separate
line. Select the statement that should be used to complete the method, so that it performs a recursive method call correctly.
Maha Otaibi 67
a)
System.out.println(value / 10);
printReverse(value / 10);
b)
System.out.println(value % 10);
printReverse(value / 10);
c)
System.out.println(value / 10);
printReverse(value % 10);
d)
System.out.println(value % 10);
printReverse(value % 10);
Answer: b
a) 6 b) 4
c) 1 d) 0
Answer: d
42) Consider the method powerOfTwo shown below:
Maha Otaibi 68
return false;
}
else
{
return powerOfTwo(n / 2); // line #3
}
}
How many recursive calls are made from the original call of powerOfTwo(64) (not including the original call)?
a) 8
b) 6
c) 4
d) 2
Answer: b
43) Complete the code for the myFactorial recursive method shown below, which is intended to compute the factorial of the
value passed to the method:
a) return(anInteger * (myFactorial(anInteger)));
b) return ((anInteger - 1) * (myFactorial(anInteger)));
c) return(anInteger * (myFactorial(anInteger - 1)));
d) return((anInteger - 1)*(myFactorial(anInteger - 1)));
Answer: c
44) Complete the code for the myFactorial recursive method shown below, which is intended to compute the factorial of the
value passed to the method:
a) if (anInteger == 1)
b) if ((anInteger - 1) == 1)
c) if (anInteger * (anInteger - 1) == 1)
d) if (myFactorial(anInteger) == 1)
Answer: a
45) Complete the code for the myFactorial recursive method shown below, which is intended to compute the factorial of the
value passed to the method:
Maha Otaibi 69
return (anInteger * myFactorial(anInteger - 1));
}
}
a) return 0;
b) return -anInteger;
c) return 1;
d) return myFactorial(anInteger);
Answer: c
46) Complete the code for the recursive method shown below, which is intended to compute the sum of the first n integers:
public int s(int n)
{
if (n == 1)
{
return 1;
}
else
{
_________________
}
}
a) return n + (n - 1);
b) return s(n) + n - 1;
c) return n + s(n - 1);
d) return n + s(n + 1);
Answer: c
47) Complete the code for the calcPower recursive method shown below, which is intended to raise the base number passed
into the method to the exponent power passed into the method:
public static int calcPower(int baseNum, int exponent)
{
int answer = 0;
________________________
{
answer = 1;
}
else
{
answer = baseNum * calcPower (baseNum, exponent - 1);
}
return answer;
}
a) if (exponent == 0)
b) if (exponent == 1)
c) if (exponent == -1)
d) if (exponent != 1)
Answer: a
48) Complete the code for the calcPower recursive method shown below, which is intended to raise the base number passed
into the method to the exponent power passed into the method:
public static int calcPower(int baseNum, int exponent)
{
int answer = 0;
if (exponent == 0)
{
_____________________
}
else
{
answer = baseNum * calcPower (baseNum, exponent - 1);
}
return answer;
}
a) answer = 0;
b) answer = 1;
c) answer = -1;
d) answer = calcPower(1);
Answer: b
Maha Otaibi 70
49) Complete the code for the calcPower recursive method shown below, which is intended to raise the base number passed
into the method to the exponent power passed into the method:
public static int calcPower(int baseNum, int exponent)
{
int answer = 0;
if (exponent == 0)
{
answer = 1;
}
else
{
_______________________________________
}
return answer;
}
a) answer = baseNum * calcPower (baseNum -1, exponent);
b) answer = baseNum * calcPower (baseNum, exponent - 1);
c) answer = baseNum * calcPower (baseNum, exponent);
d) answer = baseNum * calcPower (baseNum -1, exponent - 1);
Answer: b
Maha Otaibi 72
{
return n;
}
else
{
return (n % 10) + newCalc(n / 10);
}
}
What value will be returned when this code is executed with a call to newCalc(5)?
a) 2 b) 2.5
c) 5 d) 5.5
Answer: c
58) Complete the following code snippet, which is intended to be a recursive method that will find the smallest value in an array
of double values from index to the end of the array:
public static double minVal(double[] elements, int index)
{
if (index == elements.length - 1)
{
return elements[index];
}
double val = __________________;
if (elements[index] < val)
{
return elements[index];
}
else
{
return val;
}
}
a) minVal(elements, index - 1) b) minVal(index – 1)
c) minVal(elements, index + 1) d) minVal(index + 1)
Answer: c
59) Complete the following code snippet, which is intended to be a recursive method that will find the smallest value in an array
of double values from index to the end of the array:
public static double minVal(double[] elements, int index)
{
if (index == elements.length - 1)
{
__________________
}
double val = minVal(elements, index + 1);
if (elements[index] < val)
{
return elements[index];
}
else
{
return val;
}
}
a) return elements[index];
b) return 1;
c) return 0;
d) return elements[0];
Answer: a
60) Complete the following code snippet, which is intended to be a recursive method that will find the sum of all elements in an
array of double values from index to the end of the array:
// return the sum of all elements in arr[]
public static double findSum(double arr[], int index)
{
if (index == 0)
{
return arr[index];
Maha Otaibi 74
}
else
{
_____________________
}
}
Assume that this method would be called using an existing array named myArray as follows:
61) Complete the following code snippet, which is intended to be a recursive method that will find the sum of all elements in an
array of double values from index to the end of the array:
// return the sum of all elements in arr[]
public static double findSum(double arr[], int index)
{
if (index == 0)
{
_____________________
}
else
{
return (arr[index] + findSum(arr, index - 1));
}
}
Assume that this method would be called using an existing array named myArray as follows:
findSum(myArray,myArray.length - 1);
a) return arr[index];
b) return arr[index + 1];
c) return arr[1];
d) return arr[index - 1];
Answer: a
62) Complete the following code snippet, which is intended to be a recursive method that reverses a String value:
public static String reverseIt(String s)
{
if (s.length() <= 1)
{
_________
}
else
{
return reverseIt(s.substring(1)) + s.charAt(0);
}
}
a) return s;
b) return 0;
c) return s.charAt(0);
d) return s.substring(1);
Answer: a
63) Complete the following code snippet, which is intended to be a recursive method that reverses a String value:
public static String reverseIt(String s)
{
if (s.length() <= 1)
{
return s;
}
else
{
________________________
}
}
a) return reverseIt(s.substring(0)) + s.charAt(1);
Maha Otaibi 75
b) return reverseIt(s.substring(0)) + s.charAt(0);
c) return reverseIt(s.substring(1)) + s.charAt(1);
d) return reverseIt(s.substring(1)) + s.charAt(0);
Answer: d
64) Consider the code for the recursive method printSum shown in this code snippet, which is intended to return the sum of
digits from 1 to n:
public static int printSum(int n)
{
if (n <= 0) // line #1
{
return 0; // line #
}
else
{
return (n + printSum(n)); //line #3
}
}
Which of the following statements is correct?
a) line #1 is incorrect, and should be changed to if (n <= 1)
b) line #3 is incorrect, and should be changed to return (printSum (n - 1));
c) line #3 is incorrect, and should be changed to return (n + printSum (n + 1));
d) line #3 is incorrect, and should be changed to return (n + printSum (n - 1));
Answer: d
65) A palindrome is a word or phrase that reads the same forward or backward. Consider the methods palindrome and isPal
shown below:
public boolean palindrome(String string)
{
return isPal(string, 0, string.length() - 1);
}
66) A palindrome is a word or phrase that reads the same forward or backward. Consider the following code snippet:
public boolean palindrome(String string)
{
return isPal(string, 0, string.length() - 1);
}
Maha Otaibi 76
{
return false;
}
}
What is the purpose of the palindrome method?
a) Return the palindrome to the calling method.
b) Provide the string, along with its first and last indexes to the recursive isPal method.
c) Send the recursive isPal method its terminating condition.
d) Recursively call itself.
Answer: b
67) A palindrome is a word or phrase spelled which reads the same forward or backward. Consider the following code snippet:
public boolean palindrome(String string)
{
return isPal(string, 0, string.length() - 1);
}
68) A palindrome is a word or phrase that reads the same forward or backward. Consider the following code snippet:
public boolean palindrome(String string)
{
return isPal(string, 0, string.length() - 1);
}
Maha Otaibi 77
69) What is the purpose of a recursive helper method?
a) Shield the user of the recursive method from the recursive details.
b) Speed up the execution.
c) Eliminate the recursion.
d) Add another base case.
Answer: a
70) Consider the recursive square method shown below. It takes a non-negative int argument. Then it recursively adds the
number n to itself n times to produce the square of n. Complete the correct code for the square helper method.
public int square(int n)
{
____________________;
}
71) Consider the recursive square method shown below that takes a non-negative int argument:
a) 7 b) 13
c) 14 d) 49
Answer: a
72) Consider the recursive square method shown below that takes a non-negative int argument.
public int square(int n)
{
return square(n, n);
}
Maha Otaibi 78
return n;
}
else
{
return n + square(c - 1, n);
}
}
Assume that the last return statement is changed to this:
return n * square(c - 1, n);
What would a call to square(4) return?
a) 4
b) 16
c) 64
d) 256
Answer: d
73) Consider the helper method reversePrint, which uses recursion to display in reverse the elements in a section of an array
limited by the firstIndex and lastIndex arguments. What statement should be used to complete the recursive method?
public static void reversePrint(int[] array, int firstIndex, int lastIndex)
{
if (firstIndex < lastIndex)
{
________________________________________
}
System.out.println(array[firstIndex]);
}
public static void main(String[] args)
{
int [] numbers = { 4, 7, 1, 0, 2, 7 };
reversePrint(numbers, 0, numbers.length – 1);
}
a) reversePrint(array, firstIndex, lastIndex + 1);
b) reversePrint(array, firstIndex, lastIndex - 1);
c) reversePrint(array, firstIndex + 1, lastIndex - 1);
d) reversePrint(array, firstIndex + 1, lastIndex);
Answer: d
74) Assume that recursive method search returns true if argument value is one of the elements in the section of the array
limited by the firstIndex and lastIndex arguments. What statement can be used in main to determine if the value 7 is
one of the elements in array values?
public static boolean search(int value, int[] array, int firstIndex, int lastIndex)
{
if (firstIndex <= lastIndex)
{
if (array[firstIndex] == value)
{
return true;
}
else
{
return search(value, array, firstIndex + 1, lastIndex);
}
}
return false;
}
76) Why does the best recursive method usually run slightly slower than its iterative counterpart?
a) Testing the terminating condition takes longer.
b) Each recursive method call takes processor time.
c) Multiple recursive cases must be considered.
d) Checking multiple terminating conditions take more processor time.
Answer: b
77) Consider the fib method from the textbook shown below:
public static long fib(int n)
{
if (n <= 2)
{
return 1;
}
else
{
return fib(n – 1) + fib(n – 2);
}}
Computing the 7th fibonacci number, fib(7), recursively computes fib(6), fib(5), and fib(4) ___ times respectively.
a) 1, 2, and 3
b) 6, 5, and 4
c) 4, 5, and 6
d) 3, 2, and 1
Answer: a
Maha Otaibi 80
78) Consider the fib method from the textbook shown below.
public static long fib(int n)
{
if (n <= 2)
{
return 1;
}
else
{
return fib(n – 1) + fib(n – 2);
}
}
Calling fib(3) will trigger ___ recursive call(s) and execute the terminating condition ___ time(s), respectively.
a) 1, 1 b) 2, 2
c) 1, 2 d) 2, 1
Answer: b
79) Consider the fib method from the textbook shown below:
public static long fib(int n)
{
if (n <= 2)
{
return 1; // line #1
}
else
{
return fib(n – 1) + fib(n – 2); // line #2
}
}
Assume line #1 is changed to this:
if (n <= 2) { return 2; }
How will this change affect the result of calling fib(7)?
a) It will add 2 to the return from fib(7)
b) It will add 4 to the return from fib(7)
c) It will add 8 to the return from fib(7)
d) It will double the return from fib(7)
Answer: d
80) Consider the fib method from the textbook shown below:
public static long fib(int n)
{
if (n <= 2)
{
return 1; // line #1
}
else
{
return fib(n – 1) + fib(n – 2); // line #2
}
}
81) Consider the fib method from the textbook shown below:
public static long fib(int n)
{
if (n <= 2)
{
return 1; // line #1
}
else
Maha Otaibi 81
{
return fib(n – 1) + fib(n – 2); // line #2
}
}
82) Consider the recursive version of the fib method from the textbook shown below:
public static long fib(int n)
{
if (n <= 2)
{
return 1;
}
else
{
return fib(n – 1) + fib(n – 2);
}
}
How many recursive calls to fib(2) will be made from the original call of fib(6)?
a) 2 b) 3
c) 4 d) 5
Answer: d
83) Consider the recursive version of the fib method from the textbook shown below:
public static long fib(int n)
{
if (n <= 2)
{
return 1;
}
else
{
return fib(n – 1) + fib(n – 2);
}
}
How many total recursive calls (not counting the original call) to fib will be made from the original call of fib(6)?
a) 6 b) 12 c) 14 d) 20
Answer: c
84) Consider the recursive version of the fib method from the textbook shown below:
public static long fib(int n)
{
if (n <= 2)
{
return 1;
}
else
{
return fib(n – 1) + fib(n – 2);
}
}
How many total recursive calls (not counting the original call) to fib will be made from the original call of fib(7)?
a) 12 b) 24 c) 30 d) 32
Answer: b
85) Consider the recursive version of the fib method from the textbook shown below:
public static long fib(int n)
{
if (n <= 2)
{
Maha Otaibi 82
return 1;
}
else
{
return fib(n – 1) + fib(n – 2);
}}
How many more recursive calls to fib will be made from the original call of fib(7) than from the original call of fib(6)
(not counting the original calls)?
a) 1 b) 2
c) 5 d) 10
Answer: d
86) The method below implements the exponentiation operation recursively by taking advantage of the fact that, if the exponent n
is even, then xn = (xn/2)2. Select the expression that should be used to complete the method so that it computes the result correctly.
public static double power(double base, double exponent)
{
if (exponent % 2 != 0) // if exponent is odd
{
return base * power(base, exponent – 1);
}
else if (exponent > 0)
{
double temp = ________________________ ;
return temp * temp;
}
return base; }
a) power(base, exponent / 2)
b) power(base, exponent / 2) * power(base, exponent / 2)
c) power(base, exponent / 2) + power(base, exponent / 2)
d) power(base, exponent) / 2
Answer: a
87) Consider the iterative version of the fib method from the textbook shown below:
public static long fib(int n)
{
if (n <= 2)
{
return 1;
}
long fold = 1;
long fold2 = 1;
long fnew = 1;
for (int i = 3; i <= n; i++)
{
fnew = fold + fold2;
fold2 = fold;
fold = fnew;
}
return fnew;
}
How many iterations of the for loop will there be for the call fib(6)?
a) 6 b) 5
c) 4 d) 3
Answer: c
88) Suppose we wrote a new version of fib called newFib. What does the call newFib(6) return?
public static long newFib(int n)
{
if (n <= 3)
{
return 1;
}
else
{
return newFib(n – 1) + newFib(n – 2) + newFib(n – 3);
}}
a) 3 b) 5
c) 7 d) 9
Answer: d
Maha Otaibi 83
89) Suppose we wrote a new version of method fib, called newFib. Compare newFib to the original fib shown below:
public static long newFib(int n)
{
if (n <= 3)
{
return 1;
}
else
{
return newFib(n – 1) + newFib(n – 2) + newFib(n – 3);
}
}
94) Complete the following code snippet, which is intended to print out all permutations of the string generate by using a
permutation generator object.
public class PermutationGeneratorTester
{
public static void main(String[] args)
{
PermutationGenerator generator
= new PermutationGenerator("generate");
ArrayList<String> permutations
Maha Otaibi 84
= generator.getPermutations();
for (String s : permutations)
{
____________________
}
}}
a) generator.print();
b) generator.setPermutations();
c) generator.calculate();
d) System.out.println(s);
Answer: d
98) A unique permutation is one that is different from any other generated permutation. How many unique permutations does the
string "bee" have?
a) 2 b) 3
c) 4 d) 5
Answer: b
99) A unique permutation is one that is different from any other generated permutation. How many unique permutations does the
string "aaa" have?
a) 0 b) 1
c) 2 d) 3
Answer: b
101) Consider the following change to the PermutationGenerator class from the textbook. Instead of adding the removed
character to the front of the each permutation of the simpler word, we will add it to the end.
// Add the removed character to the end of
// each permutation of the simpler word
for (String s : shorterWordPermutations)
{
result.add(s + word.charAt(i));
}
Consider the list produced by the modified PermutationGenerator. Which best describes this list?
a) It contains all permutations.
b) It contains reversed permutations.
c) It is an incomplete list of permutations.
d) It contains strings that are not permutations.
Answer: a
Maha Otaibi 85
103) The method below generates all substrings of a String passed as argument. Assuming that the string contains no duplicate
characters, select the statement to complete the method so that it prints all substrings correctly.
public static void printSubstrings(String word)
{
if (word.length() > 0)
{
for (int j = 1; j <= word.length(); j++) // print substrings that begin
{ // with the first character
System.out.println(word.substring(0, j));
}
___________________________________ // print substrings without
} // the first character
}
a) printSubstrings(word.substring(0));
b) printSubstrings(word.substring(1));
c) printSubstrings(word.substring(word.length()));
d) printSubstrings(word.substring(word.length() - 1));
Answer: b
104) Consider the mutually recursive methods below. Select the method call that could be used to generate the output sequence:
A5 B4 A3 B2 A1
public static void methodA(int value)
{
if (value > 0)
{
System.out.print(" A" + value);
methodB(value – 1);
}
}
public static void methodB(int value)
{
if (value > 0)
{
System.out.print(" B" + value);
methodA(value – 1);
}
}
a) methodA(5); b) methodB(5);
c) methodA(4); d) methodB(4);
Answer: a
Maha Otaibi 86
public static boolean isOdd(int n)
{
if (n % 2 == 1)
{
return true;
}
else
{
return (isEven(n));
}
}
For any given value of n, what is the maximum number of function calls that could occur?
a) 0
b) 1
c) 2
d) cannot be determined
Answer: c
108) Complete the following code snippet, which is intended to determine if a value is even or odd using mutual recursion:
public static boolean isEven(int n)
{
if (n == 0)
{
return true;
}
else
{
return isOdd(Math.abs(n) - 1);
}
}
public static boolean isOdd(int n)
{
if (n == 0)
{
_________
}
else
{
return isEven(Math.abs(n) - 1);
}
}
a) return true;
b) return false;
c) return isOdd(Math.abs(n)-1);
d) return isOdd(Math.abs(n));
Answer: b
a) starts from the end of the program and works backward to the beginning.
b) starts with a partial solution and builds it up to get closer to the goal.
c) never abandons a partial solution.
d) explores only one path toward a solution
Answer: b
110) ____ is a problem-solving technique that examines partial solutions, abandons unsuitable ones, and returns to consider other
candidate solutions.
a) Debugging
b) Traceback
c) Backtracking
d) Recursion
Answer: c
Maha Otaibi 87
Chapter14: Sorting and Searching
a) sorting
b) searching
c) insertion
d) deletion
Answer: a
2) In each iteration, selection sort places which element in the correct location?
3) After 5 iterations of selection sort working on an array of 10 elements, what must hold true?
4) After one iteration of selection sort working on an array of 10 elements, what must hold true?
Maha Otaibi 88
7) Consider the sort method for selection sort shown below:
8) Consider the minimumPosition method from the SelectionSorter class. Complete the code to write a
maximumPosition method that returns the index of the largest element in the range from index from to the end of the array.
9) Consider the swap method shown below from the SelectionSorter class. If we modified it as shown in the swap2
method shown below, what would be the effect on the sort method?
Maha Otaibi 89
10) Suppose you wanted to test your sort on an array filled with different elements each time the code is run. What is an efficient
technique for creating an array of 1,000 elements for each run?
a) Run the program many times, entering different values for the array elements.
b) Make a file with many sets of values and loop through them, sorting each one.
c) Use the Random class to generate array elements, sorting each set in a loop.
d) Create many different arrays with different elements in the program code and sort each array.
Answer: c
11) After 9 iterations of selection sort working on an array of 10 elements, what must hold true?
a) The largest element is correctly placed by default.
b) One more iteration is needed to complete the sort.
c) The smallest element is incorrectly placed.
d) The largest element is incorrectly placed.
Answer: a
12) Which selection sort iteration guarantees the array is sorted for a 10-element array?
a) 9th iteration
b) 10th iteration
c) 1st iteration
d) impossible to tell
Answer: a
13) The largestPosition method below returns the index of the largest element in the tail range of an array of integers.
Select the expression that would be needed to complete the selectionSort method below, so that it sorts the elements in
descending order.
/**
Finds the largest element in the tail range of an array.
@param a the array to be searched
@param from the first position in a to compare
@return the position of the largest element in range a[from]..a[a.length – 1]
*/
private static int largestPosition(int[] a, int from)
{
int maxPos = from;
for (int j = from + 1; j < a.length; j++)
{
if (a[j] > a[maxPos])
{
maxPos = j;
}
}
return maxPos;
}
14) The code segment below is designed to add the elements in an array of integers. Select the expression needed to complete the
code segment so that it calculates the running time elapsed.
long start = System.currentTimeMillis();
int sum = 0;
for (int k = 0; k < values.length; k++)
{
sum = sum + values[k];
}
long runningTime = ____________________________;
Maha Otaibi 90
a) System.currentTimeMillis()
b) System.currentTimeMillis() - start
c) System.currentTimeMillis() + start
d) runningTime + start - System.currentTimeMillis()
Answer: b
16) Consider an array with n elements. If we visit each element n times, how many total visits will there be?
a) n
b) 2n
c) nn
d) n2
Answer: d
17) Suppose an array has n elements. We visit element #1 one time, element #2 two times, element #3 three times, and so forth.
How many total visits will there be?
a) 2n
b) n(n+1)/2
c) n2
d) n3
Answer: b
18) Suppose an algorithm requires a total of 3n3 + 2n2 – 3n + 4 visits. In big-Oh notation, the total number of visits is of what
order?
a) n2 * n2
b) n2
c) n6
d) n3
Answer: d
19) In big-Oh notation, when we consider the order of the number of visits an algorithm makes, what do we ignore?
I power of two terms
II the coefficients of the terms
III all lower order terms
a) I
b) II
c) I and II
d) II and III
Answer: d
20) In big-Oh notation, suppose an algorithm requires an order of n3 element visits. How does doubling the number of elements
affect the number of visits?
Maha Otaibi 91
23) Which of the following completes the selection sort method minimumPosition()?
private static int minimumPosition(int[] a, int from)
{
int minPos = from;
for (int i = from + 1; i < a.length; i++)
{
________________
}
return minPos;
}
a) if (a[i] > a[minPos]) { minPos = i; }
b) if (a[i] < a[minPos]) { minPos = i; }
c) if (a[i] < a[j]) { minPos = i; }
d) if (a[i] < a[minPos]) { i = minPos; }
Answer: b
24) If you increase the size of a dataset fivefold, how much longer does it take to sort it with the selection sort algorithm?
a) Approximately 5 times longer
b) Approximately 20 times longer
c) Approximately 25 times longer
d) Approximately 100 times longer
Answer: c
25) How many comparisons does selection sort make when sorting an array of length n?
a) n
b) log(2n)
c) n( n + 1) / 2
d) n
Answer: c
27) When the size of an array increases by a factor of 100, the time required by selection sort increases by a factor of ____.
a) 2,000
b) 5,000
c) 10,000
d) 12,000
Answer: c
28) Which notation, big-Oh, theta, or omega describes the growth rate of a function?
I big-Oh
II theta
III omega
a) I
b) II and III
c) I and II
d) I, II, and III
Answer: d
29) If f(n) = O(g(n)) and g(n) = O(f(n)), what else must be true?
I f(n) = Ω(g(n))
II g(n) = Ω(f(n))
III f(n) = θ(g(n))
a) I
b) II
c) I and II
d) I, II, and III
Answer: d
Maha Otaibi 92
30) In general, the expression ____ means that f grows no faster than g.
a) f(n) = log g
b) f(n) = log g2
c) f(n) = O(g(n))
d) g(n) = O(f(n))
Answer: c
31) Find the simplest order of growth of the following expression: (n3 + n + 3)2.
a) θ(n5)
b) θ(2n)
c) θ(n6)
d) θ(n9)
Answer: c
32) Find the simplest order of growth of the following expression: n3 + log(n5).
a) θ(n3)
b) θ(n3+ log(n))
c) θ(log(n5))
d) θ(n + log(n))
Answer: a
33) Choose the order of the following growth rates, from slowest to fastest: θ(n3), θ(nlog(n)), θ(n3/2), θ(2n).
a) insertion sort
b) selection sort
c) merge sort
d) quicksort
Answer: a
36) Which sort algorithm starts with an initial sequence of size 1, which is assumed to be sorted, and increases the size of the
sorted sequence in the array in each iteration?
a) insertion sort
b) selection sort
c) merge sort
d) quicksort
Answer: a
Maha Otaibi 93
37) What is the worst-case performance of insertion sort?
a) O(n)
b) O(n2)
c) O(log (n))
d) O(n log (n))
Answer: b
38) If the array is already sorted, what is the performance of insertion sort?
a) O(n)
b) O(n2)
c) O(log n)
d) O(n log n)
Answer: a
39) Which sort algorithm starts by cutting the array in half and then recursively sorts each half?
a) insertion sort
b) selection sort
c) merge sort
d) quicksort
Answer: c
40) How many times can an array with 4,096 elements be cut into two equal pieces?
a) 16
b) 12
c) 10
d) 8
Answer: b
41) How many times can an array with 729 elements be cut into three equal pieces?
a) 4
b) 5
c) 6
d) 7
Answer: c
42) The merge sort algorithm presented in section 14.4, which sorts an array of integers in ascending order, uses the merge
method which is partially shown below. Select the condition that would be needed to complete the method so that the elements are
sorted in descending order.
Maha Otaibi 94
43) In the textbook, we determined that the merge method requires a total of 5n visits. We found that the number of visits
required to sort an array of n elements is T(n) = T(n / 2) + T(n / 2) + 5n. What does T(n / 2) describe?
44) In the textbook, we found that the number of element visits for merge sort totaled
n + 5nlog2n. Let’s consider sorting 1024 elements. How many visits are needed?
a) 1.024 b) 6,144
c) 51,200 d) 52,224
Answer: d
45) In the textbook, we found that the number of element visits for merge sort totaled
n + 5n log2 n. Which of the following is the appropriate big-Oh notation for merge sort?
a) 5n log2 n
b) n + log2 n
c) n + 5n
d) n log2 n
Answer: d
46) Selection sort has O(n2) complexity. If a computer can sort 1,000 elements in 4 seconds, approximately how many seconds
will it take the computer to sort 1,000 times that many, or 1,000,000 elements?
a) 16
b) 1,000
c) 1,000,000
d) 4,000,000
Answer: d
47) Merge sort has a O(n log2(n)) complexity. If a computer can sort 1,024 elements in an amount of time x, approximately how
much longer will it take the computer to sort 1,024 times that many, or 1,048,576 elements?
a) 1,024 times longer
b) 2,048 times longer
c) 8,192 times longer
d) 1,048,576 times longer
Answer: c
48) Merge sort is a(n) ____ algorithm.
a) O(n)
b) O(n log(n))
c) O(n2)
d) O(log n)
Answer: b
49) Assume we are using quicksort to sort an array in ascending order. Into which array location does quicksort’s strategy place a
pivot element after partitioning?
a) lowest index in array still available
b) highest index in array still available
c) closer to its correct final location
d) its final correct location
Answer: d
50) Assume we are using quicksort to sort an array in ascending order. What can we conclude about the indexes of two pivot
elements placed in consecutive recursive calls?
a) They are randomly located.
b) They are in different halves of the array.
c) They are both in the same half of the array.
d) They are adjacent.
Answer: a
51) Assume we are using quicksort to sort an array in ascending order. What can we conclude about the elements to the left of the
currently placed pivot element?
a) They are all sorted.
b) They are all less than or equal to the pivot element.
c) They are all greater than or equal to the pivot element.
d) None can equal the pivot element.
Answer: b
Maha Otaibi 95
52) When does quicksort’s worst-case run-time behavior occur?
53) Which sort algorithm starts by partitioning the array and selecting a pivot element?
a) merge sort
b) quicksort
c) selection sort
d) insertion sort
Answer: b
54) A version of which sort algorithm is used in the sort method in the Java Arrays class?
a) merge sort
b) quicksort
c) selection sort
d) insertion sort
Answer: b
55) Which sort algorithm is used in the sort method in the Java Arrays class when the array length is less than 7?
a) merge sort
b) quicksort
c) selection sort
d) insertion sort
Answer: d
56) Which of the sorts in the textbook are based on the strategy of divide and conquer?
I quicksort
II mergesort
III insertion sort
a) I b) II
c) III d) I and II
Answer: d
57) Which of the sorts in the textbook can be characterized by the fact that the best case will have a running time of θ(n) if the
data is already sorted?
I quicksort
II selection sort
III insertion sort
a) I
b) II
c) III
d) I and III
Answer: c
58) Which of the sorts in the textbook can be characterized by the fact that even in the worst case the running time will be O(n
log(n)))?
I quicksort
II selection sort
III merge sort
a) I
b) II
c) III
d) I and III
Answer: c
62) Suppose you have a phone number and need to find the address that it corresponds to. If there are 2,000,000 entries, how
many do you expect to search in a printed phone directory before finding the address you are looking for?
63) If an element is present in an array of length n, how many element visits, in the worst case, are necessary to find it using a
linear search?
a) n / 2
b) n
c) 2n
d) n2
Answer: b
64) If an element is present in an array of length n, how many element visits, on average, are necessary to find it using a linear
search?
a) n / 2
b) n
c) 2n
d) n2
Answer: a
66) If you implement a recursive linear search, its performance will be ____.
a) O(n)
b) O(n2)
c) O(log (n))
d) O(n log (n))
Answer: a
Maha Otaibi 97
68) Given an ordered array with 15 elements, how many elements must be visited in the worst case of binary search?
a) 8
b) 4
c) 3
d) 2
Answer: b
69) Given an ordered array with 31 elements, how many elements must be visited in the worst case of binary search?
a) 16
b) 8
c) 5
d) 4
Answer: c
70) The analysis for the number of visits in a binary search begins with the equation,
T(n) = T(n / 2) + 1. What does the number 1 represent in this equation?
a) One element visit before a recursive call on one half of the array.
b) The total number of recursions required.
c) The fact that the number of elements is odd.
d) The fact that we search either the left half or the right half, but not both.
Answer: a
71) Suppose we are using binary search on an array with approximately 1,000,000 elements. How many visits should we expect to
make in the worst case?
a) 1 b) 16
c) 20 d) 30
Answer: c
73) A search technique where, in each step, you split the size of the search in half is called a____ search.
a) random
b) binary
c) linear
d) merging
Answer: b
74) Can you search the following array using binary search?
int[] A = {6, 5, 4, 2, 0, 1, -1, -17};
a) Yes. Binary search can be applied to any array.
b) No. Binary search can be applied to a sorted array only.
c) Yes, but the algorithm runs slower because the array is in descending order.
d) No, negative numbers are not allowed because they indicate that a value is not present.
Answer: b
75) The partial linear search method below is designed to search an array of String objects. Select the expression that would be
needed to complete the method.
public static int search(String[] a, String item)
{
for (int i = 0; i < a.length; i++)
{
if ( ____________________________ )
{
return i;
}
return -1;
}}
a) a[i] == item
b) a[i].compareTo(item)
c) a[i].equals(item)
d) a[i].indexOf(item)
Answer: c
Maha Otaibi 98
76) The partial binary search method below is designed to search an array of String objects sorted in ascending order. Select
the expression that would be needed to complete the method.
public static int search(String[] a, int low, int high, String item)
{
if (low <= high)
{
int mid = (low + high) / 2;
int result = ____________________________;
if (result == 0)
{
return mid;
}
else if (result < 0)
{
return search(a, mid + 1, high, item);
}
else
{
return search(a, low, mid - 1, item);
}
}
return -1;
}
a) a[low].compareTo(item)
b) item.equals(a[mid])
c) item.compareTo(a[mid])
d) a[mid].compareTo(item)
Answer: d
77) A portion of your program implements a loop in which each step contains a fixed number of actions. What can you conclude
about the running time of this section of code?
a) Its running time will be O(n).
b) Its running time will be O(n2).
c) Its running time will be O(log (n)).
d) Its running time will be O(n log (n)).
Answer: a
78) Which of the following statements about running times of algorithms is correct?
a) An algorithm that is O(1) means that only one comparison takes place.
b) When determining the running time, constants are not taken into consideration.
c) When determining the running time, lower-order terms must be taken into consideration.
d) An algorithm that is O(n) means that the number of comparisons does not grow as the size of the array increases.
Answer: b
79) A portion of your program includes the loop shown in the code snippet below to examine the elements of an array arr:
int count = 0;
int targetVal = 70;
for (int i = 0; i < arr.length; i++)
{
if (arr[i] >= targetVal)
{
count++;
}
}
What can you conclude about the running time of this section of code?
a) Its running time will be O(n).
b) Its running time will be O(n2).
c) Its running time will be O(log (n)).
d) Its running time will be O(n log (n)).
Answer: a
80) The method findLargest examines the elements of an array arr which contains non-negative values
public static int findLargest(int[] arr)
{
int curLargest = -1;
for (int i = 0; i < arr.length; i++)
{
if (arr[i] >= curLargest)
{
curLargest = arr[i];
Maha Otaibi 99
}
}
return curLargest;
}
What can you conclude about the running time of this section of code?
a) Its running time will be O(n).
b) Its running time will be O(n2).
c) Its running time will be O(log (n)).
d) Its running time will be O(n log (n)).
Answer: a
82) An algorithm that tests whether the first array element is equal to any of the other array elements would be an ____ algorithm.
a) O(1)
b) O(n)
c) O(log (n))
d) O(n log (n))
Answer: b
83) A portion of your program includes the loops shown in the code snippet below to examine the elements of two arrays, arr1
and arr2, both of length n:
int matches = 0;
for (int i = 0; i < arr1.length; i++)
{
for (int j = 0; j < arr2.length; j++)
{
if (arr1[i].equals(arr2[j]))
{
matches++;
}
}
}
What can you conclude about the running time of this section of code?
84) A portion of your program includes the method shown in the code snippet below to examine the elements of an array arr:
86) The code segment below prints some of the elements in an array with size n. Select an expression to complete the code
segment so that the resulting algorithm has O(log n) running time.
for __________________________
{
System.out.println(array[j]);
}
a) (int j = 0; j < array.length; j = j + 2)
b) (int j = 1; j < array.length; j = j * 2)
c) (int j = 0; j < array.length / 2; j++)
d) (int j = 0; j < array.length; j++)
Answer: b
87) The code segment below displays a pattern of asterisks. Select an expression to complete the code segment so that the
resulting algorithm has O(n) running time.
for (int k = 0; k < n; k++)
{
for _______________________
{
System.out.print("*");
}
System.out.println();
}
a) (int j = n; j > 0; j = j / 2)
b) (int j = n; j > 0; j--)
c) (int j = 1; j < k; j++)
d) (int j = 1; j <= 10; j++)
Answer: d
88) The code segment below displays a table of numbers. Select an expression to complete the code segment, so that the resulting
algorithm has O(n2) running time.
for (int k = 1; k <= n; k++)
{
for _______________________
{
System.out.print(j + " ");
}
System.out.println();
}
a) (int j = n; j > 0; j = j / 2)
b) (int j = 1; j < k; j = j * 2)
c) (int j = 0; j < k; j++)
d) (int j = 1; j <= 200; j++)
Answer: c
89) Assume that names is an array of String objects that has been initialized with a large number of elements. Select the
statement that would sort the elements in names in ascending alphabetic order.
a) Arrays.sort(names, 0, names.length - 1);
b) Arrays.sort(names);
c) Collections.sort(names, 0, names.length - 1);
d) Collections.sort(names);
Answer: b
90) Assume that bands is an ArrayList of String objects which contains a number of elements in ascending order. Select a
statement to complete the code segment below, which invokes the Java library binarySearch method to search for the string
"Beatles". If the list does not already contain the string, it should be inserted in an appropriate location so that the list remains
sorted.
91) The sort method of the Arrays class sorts arrays containing objects of classes that implement the ____ interface.
a) Sortable
b) Ordered
c) Array
d) Comparable
Answer: d
92) The ____ class contains a sort method that can sort array lists.
a) Sorting
b) Arrays
c) Collections
d) Linear
Answer: c
93) The binarySearch method of the Collections class returns a value in the form of –k - 1 when the target item you
are searching for was not found in the array. What does k represent?
a) It is the position of an existing item, and indicates that your target item should come after this existing item.
b) It is the position of an existing item, and indicates that your target item should come before this existing item.
c) It represents the number of times the array was accessed by the binarySearch method, and can be used for analyzing
performance.
d) Nothing – it is an arbitrary value.
Answer: b
96) If a call to the Arrays static method binarySearch returns a value of -10, what can be concluded?
I the element is not in the array
II the element is at index 10
III the element can be inserted at index 9
a) I
b) II
c) III
d) I and III
Answer: d
97) If a call to the Arrays static method binarySearch returns a value of 7, what can be concluded?
I the element is not in the array
II the element is at index 7
III the element occurs 7 times in the array
a) I
b) II
c) III
d) II and III
Answer: b
99) If you want to use the Comparable interface, you must implement a single method called ____.
a) comparable
b) compareTo
c) comparator
d) compare
Answer: b
I Date
II Collections
III String
a) I
b) I and II
c) I and III
d) II and III
Answer: c
101) Suppose the call obj1.compareTo(obj2) returns 0. What can definitely be concluded from the return value?
I obj1 and obj2 are the same object
II obj1 and obj2 objects cannot be compared
III the properties of obj1 and obj2 that are being compared have identical values
a) I b) II
c) I and III d) III
Answer: d
102) Which of the following arrays can be used in a call to the Arrays.sort method?
103) Suppose objects a and b are from a user-defined class that implements the Comparable interface. Which condition tests
the compareTo method’s return value to determine that a will precede b when the sort method is called?
a) a.compareTo(b) == -1
b) a.compareTo(b) == 0
c) a.compareTo(b) < 0
d) a.compareTo(b) > 0
Answer: c
104) Suppose objects a and b are from a user-defined class that implements the Comparable interface. What must be true
about the return value of a.compareTo(b) for the compareTo method that this class implements?
a) It must return 1 if a comes before b, 0 if they are the same, and -1 if a comes after b.
b) It must return -1 if a comes before b, 0 if they are the same, and 1 if a comes after b.
c) It must return a positive value if a comes before b, 0 if they are the same, and a negative value if a comes after b.
d) It must return a negative value if a comes before b, 0 if they are the same, and a positive value if a comes after b.
Answer: d
106) Suppose a developer gets class XYZ files and documentation from a subcontractor. This class does not implement the
Comparable interface. What must be true in order for the developer to sort an array of XYZ objects without modifying the xyz
class?
a) The XYZ class must implement the Sortable interface.
b) XYZ objects must be randomly distributed.
c) XYZ objects must be ordered.
d) The developer must supply a comparator object belonging to a class that implements the Comparator<XYZ> interface.
Answer: d
107) Suppose you wish to sort an array list of objects, but the object class does not implement the Comparable interface.
Because you are not allowed to modify this class, you decide to provide a comparator object that implements the Comparator
interface. Which method must you implement from this interface to achieve your objective?
a) the sort method.
b) the compare method.
c) the compareTo method.
d) the compareObject method.
Answer: b
108) Complete the following code for an interface that classes who wish to compare Auto objects can implement.
public interface Comparator<Auto>
{
_____________________
}
a) boolean compare(Auto a, Auto b);
b) single compareTo(Auto a, Auto b);
c) int compare(Auto a, Auto b);
d) single compare(Auto a, Auto b);
Answer: c
109) When your class implements a comparator object, you must implement the compare method. What must be true about the
return value from this method when comparing two objects, a and b with a call to a.compare(b)?
a) It must return 1 if a comes before b, 0 if they are the same, and -1 if a comes after b.
b) It must return -1 if a comes before b, 0 if they are the same, and 1 if a comes after b.
c) It must return a positive value if a comes before b, 0 if they are the same, and a negative value if a comes after b.
d) It must return a negative value if a comes before b, 0 if they are the same, and a positive value if a comes after b.
Answer: d
110) Complete the following code that is intended to provide a comparator interface that will be used to create an object that
implements the Comparator interface so that object can compare Auto objects.
___________________________
{
int compare(Auto a, Auto b);
}
a) public class Comparator<Auto>
b) public class Comparator<Auto> implements Comparator
c) public interface Auto<Comparator>
d) public interface Comparator<Auto>
Answer: d
6) A collection that allows items to be added only at one end and removed only at the other end is called a ____.
a) list
b) stack
c) set
d) queue
Answer: d
7) A collection that remembers the order of items, and allows items to be added and removed only at one end is called a ____.
a) list
b) stack
c) set
d) queue
Answer: b
8) A collection that allows speedy insertion and removal of already-located elements in the middle of it is called a ____.
a) linked list
b) stack
c) set
d) queue
Answer: a
9) Which data structure would best be used for keeping track of a growing set of groceries to be purchased at the food market?
a) queue
b) stack
c) list
d) array
Answer: c
if ______________________________________
System.out.print(name + " is one of the players in the collection.");
a) (players.indexOf(name))
b) (players.contains(name))
c) (players.search(name))
d) (players.equals(name))
Answer: b
13) We might choose to use a linked list over an array list when we will not require frequent ____.
I random access
II inserting new elements
III removing of elements
a) I
b) II
c) III
d) II and III
Answer: a
14) Which nodes need to be updated when we insert a new node to become the fourth node from the beginning of a doubly-linked
list?
a) The current third node.
b) The current third and fourth nodes.
c) The current first node.
d) The current fourth and fifth nodes.
Answer: b
15) A binary search requires ____ access.
a) sequential
b) random
c) sorted
d) arbitrary
Answer: b
17) Rather than storing values in an array, a linked list uses a sequence of ____.
a) indexes
b) nodes
c) elements
d) accessors
Answer: b
19) What type of access does a LinkedList provide for its elements?
a) sequential
b) semi-random
c) random
d) sorted
Answer: a
a) abcdefghi
b) ghiabcdef
c) abcghidef
d) defghiabc
Answer: b
a) abcdefghi
b) ghiabcdef
c) abcghidef
d) defghiabc
Answer: d
22) The term ____ is used in computer science to describe an access pattern in which the elements are accessed in arbitrary order.
a) sequential access
b) random access
c) sorted access
d) arbitrary access
Answer: b
26) Assume you have created a linked list name myList that currently holds some number of String objects. Which of the
following statements correctly removes an element from the end of myList?
a) myList.remove();
b) myList.removeLast();
c) myList.getLast();
d) myList.pop();
Answer: b
27) A(n) ____ is a data structure used for collecting a sequence of objects that allows efficient addition and removal of already-
located elements in the middle of the sequence.
a) stack b) queue
c) linked list d) priority queue
Answer: c
28) What is the meaning of the type parameter E, in the LinkedList<E> code fragment?
a) The elements of the linked list are of class E.
b) The elements of the linked list are of any subclass of class E.
c) The elements of the linked list are any type supplied to the constructor.
d) The elements of the linked list are of class Object.
Answer: c
30) Consider the code snippet shown below. Assume that employeeNames is an instance of type LinkedList<String>.
for (String name : employeeNames)
{
// Do something with name here
}
Which element(s) of employeeNames does this loop process?
a) no elements
b) all elements
c) elements meeting a condition
d) the most recently added elements
Answer: b
32) Select an appropriate expression to complete the following code segment, which is designed to print a message if the string
stored in name is the first element of the players linked list.
LinkedList<String> players = new LinkedList<String>();
// code to add elements to the linked list
if ______________________________________
System.out.print(name + " is the first player on the list.");
a) (players.indexOf(name) == 1)
b) (players.contains(name))
c) (players.getFirst().equals(name))
d) (players[0].equals(name))
Answer: c
while (______________________)
{
if (iter.next().equals(name))
{
number++;
}
}
return number;
}
a) iter.hasNext()
b) iter.next() != null
c) theList.hasNext()
d) theList.next() != null
Answer: a
34) Select an appropriate expression to complete the following method, which is designed to visit the elements in theList and
replace each occurrence of the string "hello" with the string "goodbye".
a) iterator.replace("hello", "goodbye");
b) iterator.next() = "goodbye";
c) iterator.previous("goodbye");
d) iterator.set("goodbye");
Answer: d
35) When using a list iterator, on which condition will the IllegalStateException be thrown?
a) Calling remove after calling next.
b) Calling next after calling previous.
c) Calling remove after calling remove.
d) Calling remove after calling previous.
Answer: c
36) When using a list iterator, on which condition will the IllegalStateException be thrown?
a) Calling remove after calling next.
b) Calling add after calling previous.
c) Calling remove after calling add.
d) Calling previous after calling previous.
Answer: c
37) Which of the following statements about the LinkedList class is correct?
a) When you use the add method, the new element is inserted before the iterator, and the iterator position is advanced by one
position.
b) When you use the add method, the new element is inserted after the iterator, and the iterator position is advanced by one
position.
c) When you use the add method, the new element is inserted before the iterator, and the iterator position is not moved
d) When you use the add method, the new element is inserted after the iterator, and the iterator position is not moved.
Answer: a
39) A linked list ____ encapsulates a position anywhere inside the linked list.
a) accessor
b) index
c) operation
d) iterator
Answer: d
40) You use a(n) ____ to access elements inside a linked list.
a) accessor
b) index
c) list iterator
d) queue
Answer: c
41) A linked list allows ____ access, but you need to ask the list for an iterator.
a) sequential
b) random
c) sorted
d) arbitrary
Answer: a
42) The nodes of a(n) ____ linked list class store two links: one to the next element and one to the previous one.
a) array
b) singly
c) doubly
d) randomly
Answer: c
43) Assume you are using a doubly-linked list data structure with many nodes. What is the minimum number of node references
that are required to be modified to remove a node from the middle of the list? Consider the neighboring nodes.
a) 1
b) 2
c) 3
d) 4
Answer: b
44) In a linked list data structure, when does the reference to the first node need to be updated?
a) Inserting and removing elements that have already been located is faster with a list than with a set.
b) Accessing elements in a linked list in a random fashion is efficient.
c) Adding and removing already-located elements in the middle of a linked list is efficient.
d) A set is an ordered collection of unique elements.
Answer: c
a) Inserting and removing elements that have already been located is faster with a list than with a set.
b) A set allows duplicate values.
c) You can add an element to a specific position within a set.
d) A set is a collection of unique elements organized for efficiency.
Answer: d
48) Which of the following statements about hash tables is NOT correct?
a) Elements are grouped into smaller collections that share the same characteristic.
b) You can form hash tables holding objects of type String.
c) You can add an element to a specific position within a hash table.
d) The value used to locate an element in a hash table is called a hash code.
Answer: c
49) Which of the following statements about the TreeSet class is NOT correct?
a) Elements are stored in sorted order.
b) Elements are arranged in linear fashion.
c) Elements are stored in nodes.
d) To use a TreeSet, it must be possible to compare the elements.
Answer: b
50) Select an appropriate declaration to complete the following code segment, which is designed to read strings from standard
input and display them in increasing alphabetical order, excluding any duplicates.
_________________________________________
Scanner input = new Scanner(System.in);
while (input.hasNext())
{
words.add(input.next());
}
System.out.print(words);
a) LinkedList<String> words = new LinkedList<String>();
b) Set<String> words = new Set<String>();
c) Set<String> words = new HashSet<String>();
d) Set<String> words = new TreeSet<String>();
Answer: d
51) Select an appropriate expression to complete the following method, which is designed to return the number of elements in the
parameter array numbers. If a value appears more than once, it should be counted exactly once.
public static int countElementsOnce(int[] numbers)
{
Set<Integer> values = new HashSet<Integer>();
for (int num: numbers)
{
values.add(num);
}
______________________
}
a) return numbers.length;
b) return values.length();
c) return values.size();
d) return numbers.length – values.size();
Answer: c
Maha Otaibi 111
52) To create a TreeSet for a class of objects, the object class must ____.
a) create an iterator.
b) implement the Comparable interface.
c) implement the Set interface.
d) create a Comparator object.
Answer: b
53) Which of the following statements about manipulating objects in a set is correct?
a) If you try to add an element that already exists, an exception will occur.
b) If you try to remove an element that does not exist, an exception will occur.
c) You can add an element at the position indicated by an iterator.
d) A set iterator visits elements in the order in which the set implementation keeps them.
Answer: d
54) Which of the following statements about manipulating objects in a set is correct?
a) If you try to add an element that already exists, an exception will occur.
b) A set iterator visits elements in the order in which they were added to the set.
c) You can add an element at the position indicated by an iterator.
d) You can remove an element at the position indicated by an iterator.
Answer: d
55) Assume that you have declared a set named mySet to hold String elements. Which of the following statements will
correctly insert an element into mySet?
a) mySet.insert("apple");
b) mySet.put(apple");
c) mySet.push("apple");
d) mySet.add("apple");
Answer: d
56) Assume that you have declared a set named mySet to hold String elements. Which of the following statements will
correctly remove an element from mySet?
a) mySet.get("apple");
b) mySet.remove("apple");
c) mySet.pop("apple");
d) mySet.delete("apple");
Answer: b
57) Complete the following code snippet, which is intended to determine if a specific value in a variable named targetWord
appears in a set of String values named mySet:
58) Which of the following statements about manipulating objects in a map is NOT correct?
a) Use the add method to add a new element to the map.
b) Use the get method to retrieve a value from the map.
c) Use the keyset method to get the set of keys for the map.
d) Use the remove method to remove a value from the map.
Answer: a
59) Complete the following code, which is intended to print out all key/value pairs in a map named myMap that contains String
data for student IDs and names:
Map<String, String> myMap = new HashMap<String, String>();
. . .
_______________________________
for (String aKey : mapKeySet)
{
String name = myMap.get(aKey);
System.out.println("ID: " + aKey + "->" + name);
60) Complete the following code, which is intended to print out all key/value pairs in a map named myMap that contains String
data for student IDs and names:
Map<String, String> myMap = new HashMap<String, String>();
. . .
61) Assume that you have declared a map named myMap to hold String elements with Integer keys. Which of the following
statements will correctly insert an element into myMap?
a) myMap.insert(3, "apple");
b) myMap.put(3, "apple");
c) myMap.push(3, "apple");
d) myMap.add(3, "apple");
Answer: b
62) Assume that you have declared a map named myMap to hold String elements with Integer keys. Which of the following
statements will correctly remove an element from myMap?
a) myMap.get(3);
b) myMap.remove(3);
c) myMap.pop(3);
d) myMap.delete(3);
Answer: b
63) Assume that you have declared a map named myMap to hold String elements with Integer keys. Which of the following
statements will correctly retrieve the value of an element from myMap by using its key?
a) myMap.get("apple");
b) myMap.peek("apple");
c) myMap.get(3);
d) myMap.peek(3);
Answer: c
64) Your program uses a Map structure to store a number of user ids and corresponding email addresses. Although each user must
have a unique id, two or more users can share the same email address. Select an appropriate expression to complete the method
below, which adds a new id and email address to the map only if the id is not already in use. If the id is already in use, an error
message is printed.
public static void addUserID(Map<String, String> users, String id, String email)
{
String currentEmail = users.get(id);
if (___________________)
{
users.put(id, email);
}
else
{
System.out.println(id + " is already in use.");
}
}
a) currentEmail.equals(email)
b) !currentEmail.equals(email)
c) currentEmail == null
Maha Otaibi 113
d) currentEmail != null
Answer: c
65) Which of the following statements about manipulating objects in a map is NOT correct?
a) If you attempt to retrieve a value with a key that is not associated with any value, you will receive a null result.
b) You cannot change the value of an existing association in the map; you must delete it and re-add it with the new values.
c) Use the get method to retrieve a value associated with a key in the map.
d) Use the put method to add an element to the map.
Answer: b
If you need to visit the keys in sorted order, which of the following statements will create a structure to support this?
a) scores = new HashMap<String, Integer>;
b) scores = new TreeMap<String, Integer>;
c) scores = new Map<String, Integer>;
d) scores = new HashTable<String, Integer>;
Answer: b
68) You want to enumerate all of the keys in a map named myMap whose keys are type String. Which of the following
statements will allow you to do this?
a)
Set<String> keySet = myMap.keySet();
for (String key : keySet) {. . . }
b)
Set<String> keySet = myMap.getKeys();
for (String key : keySet) {. . . }
c)
Set<String> keySet = myMap.keys();
for (String key : keySet) {. . . }
d)
Set<String> keySet = myMap.getKeySet();
for (String key : keySet) {. . . }
Answer: a
69) You need to access values by an integer position. Which collection type should you use?
a) Map
b) Hashtable
c) ArrayList
d) Queue
Answer: c
70) You need to access values in objects by a key that is not part of the object. Which collection type should you use?
a) Map
b) Hashtable
c) ArrayList
d) Queue
Answer: a
71) You need to access values in the order in which they were added (first in, first out), and not randomly. Which collection type
should you use?
a) Map
b) Hashtable
c) Stack
d) Queue
Answer: d
73) You need to access values using a key, and the keys must be sorted. Which collection type should you use?
a) TreeMap
b) ArrayList
c) HashMap
d) Queue
Answer: a
74) You need to access values by their position. Which collection type should you use?
a) TreeSet
b) ArrayList
c) Stack
d) Queue
Answer: b
74) You have decided to store objects of a class in a TreeSet structure. Which of the following statements is correct?
a) If the object class implements the Comparable interface, and the sort order in the compare method is acceptable, you do not
have to do anything else.
b) If the object class implements the Comparable interface, and the sort order in the compareTo method is acceptable, you do
not have to do anything else.
c) If the object class implements the Comparable interface, and the sort order in the compare method is acceptable, you must
create a comparator object.
d) If the object class implements the Comparable interface, and the sort order in the compareTo method is acceptable, you
must create a comparator object.
Answer: b
75) Which data structure would best be used for storing a set of numbers and sorting them in ascending order?
a) queue
b) stack
c) list
d) array
Answer: d
78) You need to write a program to simulate the effect of adding an additional cashier in a supermarket to reduce the length of
time customers must wait to check out. Which data structure would be most appropriate to simulate the waiting customers?
a) map
b) stack
c) queue
d) linked list
Answer: c
79) You need to write a program to build and maintain an address book. Since the program must support the possibility of having
duplicate names, which data structure would be most appropriate to model this situation?
a) map
b) stack
c) queue
d) linked list
Answer: d
81) You need to write a program to manage a waiting list of patrons at a restaurant. Which data structure would be most
appropriate to model this situation?
a) map
b) stack
c) queue
d) linked list
Answer: c
82) You intend to use a hash set with your own object class. Which of the following statements is NOT correct?
a) You do not have to do anything additional. You can use the hashCode function of the Object class.
b) You can create your own function to compute a hashCode value.
c) You can override the hashCode method in the Object class to provide your own hashCode method.
d) Your class's hashCode method does not need to be compatible with its equals method.
Answer: d
83) Which of the following statements about hash functions is NOT correct?
a) A hash function produces a unique integer-valued hash code value for each distinct object.
b) A good hash function will minimize the number of objects that are assigned the same hash code.
c) Using a prime number as a hash multiplier will produce better hash codes.
d) If you supply your own hashCode method for a class, it must be compatible with that class's equals method.
Answer: a
85) An Undo feature in a word processor program that allows you to reverse a previously completed command is probably
implemented using which structure type?
a) queue
b) linked list
c) stack
d) hash table
Answer: c
86) Which of the following correctly declares a stack that will hold String elements?
a) Stack<String> s = new Stack<String>();
b) Stack s = new Stack<String>();
c) String s = new Stack<String>();
d) String s = new Stack();
Answer: a
87) Assume that you have declared a stack named myStack to hold String elements. Which of the following statements will
correctly add an element to myStack?
a) myStack.put("apple");
b) myStack.addItem("apple");
c) myStack.push("apple");
d) myStack.insert("apple");
Answer: c
88) Assume that you have declared a stack named myStack to hold String elements. Which of the following statements will
correctly remove an element from myStack?
a) myStack.remove();
b) myStack.get();
c) myStack.delete();
d) myStack.pop();
Answer: d
92) Which data structure would best be used for finding a path out of a maze?
a) queue
b) stack
c) list
d) array
Answer: b
93) Which operations from the list data structure could be used to implement the push and pop operations of a stack data
structure?
I addLast
II addFirst
III removeFirst
a) I
b) II
c) I and II
d) II and III
Answer: d
a) ab,abc,a,
b) a,abc,ab,
c) a,ab,abc,
d) abc,ab,a,
Answer: b
95) Print jobs submitted to a printer would probably be stored in which type of data structure?
a) queue
b) linked list
c) stack
d) hash table
Answer: a
96) Assume that you have declared a queue named myQueue to hold String elements. Which of the following statements will
correctly remove an element from myQueue?
a) myQueue.remove();
b) myQueue.get();
c) myQueue.delete();
d) myQueue.pop();
Answer: a
97) Assume that you have declared a queue named myQueue to hold String elements. Which of the following statements will
correctly insert an element into myQueue?
a) myQueue.insert("apple");
b) myQueue.put("apple");
c) myQueue.push("apple");
d) myQueue.add("apple");
Answer: d
98) Select an appropriate expression to complete the method below, which is designed to print the element at the bottom of a
Stack collection. The contents of the original stack are restored before the method terminates. It is safe to assume that the
original stack contains at least one element.
a) System.out.println(theStack.pop());
b) System.out.println(theStack.peek());
c) System.out.println(anotherStack.peek());
d) System.out.println(anotherStack.pop());
Answer: c
a) names.add(aQueue.remove());
b) names.add(aQueue.peek());
c) aQueue.add(names.remove());
d) aQueue.add(names.peek());
Answer: a
100) Select an appropriate expression to complete the following method, which is designed to return the sum of the two smallest
values in the parameter array numbers.
101) Suppose you push integer elements 1,2,3,4 onto a stack in that order. Then pop an element off the stack and add that element
to a queue. You repeat that process three more times. In what order will you remove the elements from the queue?
a) 1,2,3,4
b) 1,2,4,3
c) 4,3,2,1
d) 4,3,1,2
Answer: c
102) Which data structure would best be used for keeping track of bank customers waiting for a teller?
a) queue
b) stack
c) list
d) array
Answer: a
103) Suppose we have two String objects and treat the characters in each string from beginning to end in the following way:
With one string, we push each character on a stack. With the other string, we add each character to a queue. After processing both
strings, we then pop one character from the stack and remove one character from the queue, and compare the pair of characters to
each other. We do this until the stack and the queue are both empty. What does it mean if all the character pairs match?
105) Suppose we create a deque (double-ended queue) data structure. It is basically a queue, with its addLast and
removeFirst operations, but we also add the addFirst and removeLast operations. Which of the following is best
modeled by the deque data structure?
a) A toll booth on a highway.
b) A cross country race.
c) A computer keyboard typing buffer.
d) A Memorial Day parade.
Answer: c
106) Suppose we create a deque (double-ended queue) data structure. It is basically a queue, with its addLast and
removeFirst operations, but we also add the addFirst and removeLast operations. If a line at the grocery store
resembles a deque more than a queue, what is the most likely reason?
a) I
b) II
c) I and II
d) II and III
Answer: d
107) Which of the following statements about a priority queue structure is correct?
a) It uses a FIFO discipline.
b) New items must be inserted at the end of the queue.
c) Elements must be removed in priority order.
d) It uses a LIFO discipline.
Answer: c
108) Which of the following statements about a priority queue structure is NOT correct?
a) Elements added to a priority queue must belong to a class that implements the Comparable interface.
b) New elements can be inserted in any order.
c) The remove method is used to remove an element from the priority queue.
d) The insert method is used to add a new element to the priority queue.
Answer: d
a) ab,abc,a,
b) a,abc,ab,
c) a,ab,abc,
d) abc,ab,a,
Answer: c
2) In the textbook implementation, the Node class is a private inner class of the LinkedList class. Which of the following
statements regarding this implementation is NOT correct?
a) The methods of the LinkedList class can access the public features of the Node class.
b) The methods of the Node class can access the public features of the LinkedList class.
c) The methods of the Node class can be directly accessed by other classes.
d) The Node class's instance variables that represent the node element and its next node reference are declared as public.
Answer: c
4) Insert the missing code in the following code fragment. This fragment is intended to add a new node to the head of a linked list:
5) Insert the missing code in the following code fragment. This fragment is intended to remove a node from the head of a linked
list:
public class LinkedList
{
. . .
public Object removeFirst()
{
if (first == null) { throw new NoSuchElementException(); }
Object element = first.data;
________________
________________
Maha Otaibi 121
}
. . .
}
a)
first = first.next; 1
return element;
b)
first.next = first; 1
return element;
c)
first = element.next; 1
return element;
d)
first = element.next; 1
return null;
Answer: a
6) Insert the missing code in the following code fragment. This fragment is intended to remove a node from the head of a linked
list:
public class LinkedList
{
. . .
public Object removeFirst()
{
if (first == null) { ________________ }
Object element = first.data;
first = first.next; 1
return element;
}
. . .
}
a) throw new NoSuchElementException();
b) throw new IllegalStateException();
c) throw new NullPointerException();
d) throw new IllegalArgumentException();
Answer: a
7) Which of the following statements about removing a node from a linked list is correct?
a) A node's data is discarded when it is removed from the linked list, and its memory space is immediately reclaimed.
b) A node's data is returned to the program when the node is removed from the linked list, and its memory space is immediately
reclaimed.
c) A node's data is discarded when it is removed from the linked list, and its memory space is reclaimed later by the garbage
collector.
d) A node's data is returned to the program when the node is removed from the linked list, and its memory space is reclaimed later
by the garbage collector.
Answer: d
8) In the textbook implementation, the LinkedListIterator class is a private inner class of the LinkedList class. Which
of the following statements regarding this implementation is NOT correct?
a) The methods of the LinkedList class can access the public features of the LinkedListIterator class.
b) The methods of the LinkedListIterator class can access the public features of the LinkedList class.
c) The methods of the LinkedListIterator class can be directly accessed by other classes.
d) Clients of the LinkedListClass do not know the name of the LinkedListIterator class.
Answer: c
9) The linked list iterator described in the textbook maintains a reference to the last visited node, called position, and a
reference to the last node before that, called previous. Which of the following statements is NOT correct regarding advancing
this iterator?
a) If another node exists, when the iterator is to be advanced, the position reference must be updated to position.next.
b) If the iterator currently points before the first element of the list, when the iterator is to be advanced, position must be set to
point to the first node in the linked list.
c) If another node exists, when the iterator is to be advanced, the previous reference must be updated to point to the current
location of the iterator
d) If the iterator currently points before the first element of the list, when the iterator is to be advanced, the position reference
must be set to position.next and the previous reference must be set to point to the first node in the linked list.
Answer: d
a) The iterator is at the end of the list if the linked list's first node reference is null.
b) The iterator is at the end of the list if the position.next reference is null.
c) The iterator is at the end of the list if the position reference is null.
d) The list is empty if the linked list's first node reference is null.
Answer: c
11) Which of the following statements about a linked list and its iterator is NOT correct?
a) The list is empty if the linked list's first node reference is null.
b) The iterator is at the end of the list if the position.next reference is null.
c) The iterator is at the beginning of the list if the previous reference is null.
d) The iterator is at the first node of the list if its position reference is null.
Answer: d
12) Using the textbook's implementation of a singly linked list and linked list iterator, the following steps are required to remove a
node from the middle of a linked list. Place these steps into the order in which they should be performed.
I The preceding node's next reference must be updated to skip the removed node.
II The iterator's position reference must be set to the previous reference.
III The previous reference must be checked to see if it is equal to the position reference.
a) III, I, II
b) I, III, II
c) II, I, III
d) III, II, I
Answer: a
13) When using the textbook’s implementation of a singly linked list to remove an element in the middle of the list, why it is
necessary to check whether the previous reference equals the position reference?
a) If previous equals position, the action does not follow a call to next.
b) If previous equals position and an attempt is made to remove the node, the iterator would have to start at the beginning
of the list to rebuild the links.
c) If previous equals position, the iterator is at the beginning of the list and does not point to a valid node.
d) If previous equals position, the iterator is at the end of the list and does not point to a valid node.
Answer: a
14) Using the textbook's implementation of a linked list, which of the following statements about adding a node to the middle of a
linked list is correct?
a) The new node will be added before the last visited node.
b) The position.next reference will be updated to point to the new node.
c) The remove method can be called immediately before or after adding the new node.
d) The previous reference must be updated when adding the new node.
Answer: b
17) Using the textbook's implementation of a linked list, which of the following statements about changing the data stored in a
previously visited element is correct?
a) The node that will be updated is the most recently visited node.
b) The position.next reference must be updated when the data is updated.
c) The set method can be called again immediately after calling the add method.
d) The previous reference must be updated when the node is updated.
Answer: a
18) Using the textbook's implementation of a linked list, which of the following statements about managing nodes within a linked
list using an iterator is correct?
a) The node that will be removed is the node pointed to by the position.next reference.
b) The set method can be called immediately after adding a new node using the add method.
c) The set method can be called immediately after removing an existing node using the remove method.
d) The position reference must be updated when a new node is added.
Answer: d
19) Assume that the linked list implementation includes a reference to the last node as well as to the first node. Which of the
following statements about the efficiency of the linked list is correct?
a) Adding an element to the middle of the linked list at the current position of the iterator is O(n).
b) Removing an element other than the last element from the linked list at the current position of the iterator is O(n).
c) Accessing an element in the linked list using an iterator is O(n).
d) Adding an element to the end of the linked list is O(1).
Answer: d
20) Assume that the linked list implementation includes a reference to the last node as well as to the first node. Which of the
following statements about the efficiency of a singly linked list is NOT correct?
a) Adding an element to the middle of a linked list using an iterator is O(1).
b) Removing the last element from a linked list using an iterator is O(1).
c) Accessing an element in a linked list using an iterator is O(n).
d) Adding an element to the end of a linked list is O(1).
Answer: b
23) What type of access does the use of an iterator with a LinkedList provide for its elements?
a) sequential
b) semi-random
c) random
d) sorted
Answer: a
24) Adding or removing an element at an arbitrary iterator position in a singly linked list of length n takes ____ time.
a) O(n)
b) O(log n)
c) O(1)
d) O(n2)
Answer: c
26) If we want a create a doubly-linked list data structure so that we can move from a node to the next node as well as to a
previous node we need to add a previous reference to the Node class. Each such DNode (doubly-linked Node) will have a data
portion and two DNode references, next and previous. How many references need to be updated when we remove a node
from the beginning of a list with many nodes? Consider the first reference and neighboring node(s).
a) 1 b) 2
c) 3 d) 4
Answer: b
27) In a linked list data structure, when does the reference to the first node need to be updated?
I inserting into an empty list
II deleting from a list with one node
III deleting an inner node
a) I
b) II
c) I and II
d) III
Answer: c
28) Suppose we maintain a linked list of length n in sorted order. What would be the big-Oh notation for the add operation?
a) O(1)
b) O(n)
c) O(n log2 n)
d) O(n2)
Answer: b
29) Suppose we maintain two linked lists of length n in sorted order. What would be the big-Oh notation for the creating a third
list, which included only elements common to both lists?
a) O(1)
b) O(n)
c) O(n log2 n)
d) O(n2)
Answer: b
30) Suppose we maintain two linked lists of length n in random element order. What would be the big-Oh notation for the creating
a third list that includes only elements common to both lists, without sorting the first two lists?
a) O(1)
b) O(n)
c) O(n log2 n)
d) O(n2)
Answer: d
31) Suppose we maintain a linked list of length n in random element order. What would be the big-Oh notation for an algorithm
that prints each list element and the number of times it occurs in the list (without sorting the list)?
a) O(1)
b) O(n)
c) O(n log2 n)
d) O(n2)
Answer: d
32) Suppose we maintain a linked list of length n in random element order. What would be the big-Oh notation for printing out
those elements which occur exactly once in the list (without sorting the list)?
a) O(1)
b) O(n)
c) O(nlog2n)
d) O(n2)
Answer: d
33) Suppose we maintain a linked list of length n in sorted order. What would be the big-Oh notation for printing out those
elements that occur exactly once in the list?
a) O(1)
b) O(n)
c) O(n log2 n)
Maha Otaibi 125
d) O(n2)
Answer: b
34) A doubly-linked list requires that each node maintain two references, one to the next node and one to the previous node.
Which of the following statements about a doubly-linked list is NOT correct?
a) If a node's next reference is null, it is at the end of the list.
b) To remove a node in the middle of the list, the previous node's next reference must be updated.
c) To add a node in the middle of the list, you must update the next reference of the node after which the new node will be added.
d) To remove a node in the middle of the list, the previous node's previous reference must be updated.
Answer: d
35) Which of the following actions must be taken to remove a node X from the middle of a doubly-linked list?
I Update the next reference in the node before X
II Update the previous reference in the node after X
III Update the list's first reference
a) I
b) II
c) I and II
d) II and III
Answer: c
36) Which of the following actions must be taken to add a node X into the middle of a doubly-linked list?
I Update the next reference in the node before the position where X will be placed
II Update the previous reference in the node after the position where X will be placed
III Update the list's first reference
a) I
b) II
c) I and II
d) II and III
Answer: c
37) Which of the following actions must be taken to add a node X at the beginning of a doubly-linked list?
I Update the next reference in the node before the position where X will be placed
II Update the previous reference in the node after the position where X will be placed
III Update the list's first reference
a) I
b) II
c) I and II
d) II and III
Answer: d
38) Which of the following actions must be taken to add a node X at the end of a doubly-linked list?
I Update the next reference in the node before the position where X will be placed
II Update the previous reference in the node before the position where X will be placed
III Update the list's last reference
a) I
b) II
c) I and II
d) I and III
Answer: d
39) Using the textbook's implementation of a linked list, what is the purpose of declaring the Node class to be a static inner
class?
a) To create an outer-class reference.
b) To create a this reference to itself.
c) To prevent storage of an outer-class reference that is not needed.
d) To create an outer-class reference that is needed.
Answer: c
40) Using the textbook's implementation of a linked list, why is the LinkedListIterator inner class NOT declared as an
inner static class?
a) Because the LinkedList class must have access to the instance variables of the LinkedListIterator class.
b) Because the Node class must have access to the instance variables of the LinkedListIterator class.
c) Because the LinkedListIterator class must have access to Node class instance variables.
d) Because the LinkedListIterator class must have access to LinkedList class instance variables.
Answer: d
42) Given the partial LinkedList class declaration below, select a statement to complete the printFirst method, which is
designed to display the contents of the first list element.
public class LinkedList
{
class Node
{
public Object data;
public Node next;
}
43) Given the partial LinkedList class declaration below, select an expression to complete the empty method, which is
designed to return true if the list contains no elements.
public class LinkedList
{
class Node
{
public Object data;
public Node next;
}
44) Given the partial LinkedList class declaration below, select a statement to complete the size method, which is designed
to return the number of list elements.
a) temp = temp.next;
b) temp = first.next;
c) first = temp.next;
d) first = first.next;
Answer: a
45) Given the partial LinkedList and LinkedListIterator class declarations below, select an expression to complete
the LinkedList get(index) method, which returns the element at the position indicated by index.
public LinkedListIterator()
{
. . .
}
a) it.next()
b) it.previous
c) it.position
d) it.next().data
Answer: a
public ArrayList()
{
final int INITIAL_SIZE = 10;
elements = new Object[INITIAL_SIZE];
currentSize = 0;
}
a) elements.length == 0
b) elements.currentSize == 0
c) elements[0] == null
d) currentSize == 0
Answer: d
47) Given the partial ArrayList class declaration below, select an expression to complete the contains method.
public ArrayList()
{
final int INITIAL_SIZE = 10;
elements = new Object[INITIAL_SIZE];
currentSize = 0;
}
a) i < currentSize
b) i <= currentSize
c) i < elements.length
d) i <= elements.length
Answer: a
a) buffer
b) tree map
c) hash table
d) bucket
Answer: a
a) O(log (n))
b) O(n)
c) O(n2)
d) O(1)
Answer: d
The ith element is the maximum in the array. What would be the lowest big-Oh notation for finding that element? Consider a
variation of the binary search.
a) O(1)
b) O(log2 n)
c) O(n)
d) O(n2)
Answer: b
51) What feature of the ArrayList class makes it much better for a binary search than the LinkedList class?
a) indexing
b) has no link references
c) it is a generic class
d) it is an abstract class
Answer: a
52) Array lists and linked lists both have the same ____.
a) add/remove efficiency
b) concrete implementations
c) random element access efficiency
d) linear traversal step efficiency
Answer: d
53) Adding or removing an arbitrary element in the middle of an array list takes ____ time.
a) O(n)
b) O(1)
c) O(log(n))
d) O(n2)
Answer: a
54) On average, how many elements of an array list of size n need to be moved when an element is removed?
a) n
b) n2
c) 2n
d) n / 2
Answer: d
55) On average, how many elements of an array list of size n need to be moved when an element is added?
a) n
b) n2
c) 2n
d) n / 2
Answer: d
56) If the current size of an array list is less than the length of the buffer, adding an element at the end of an array list takes ____
time.
a) O(n)
b) O(1)
c) O(log(n))
d) O(n2)
Answer: b
57) When the buffer for an array list must be grown, a single reallocation operation takes ____ time.
a) O(n)
b) O(1)
c) O(log(n))
d) O(n2)
Answer: a
Maha Otaibi 130
58) When considering the reallocation operation for a list whose buffer is full, on average it will take ____ time.
a) O(n)
b) O(1)
c) O(1)+
d) O(n2)
Answer: c
59) Which of the following statements about array list and doubly-linked list operations is correct?
a) It is more efficient to add an element in the middle of an array list than a doubly-linked list.
b) It is more efficient to add an element to the beginning of an array list than a doubly-linked list.
c) It is more efficient to remove an element in the middle of an array list than a doubly-linked list.
d) It is more efficient to retrieve an element in the middle of an array list than a doubly-linked list.
Answer: d
60) Array list operations that were studied included adding/removing an element at the end or in the middle, and retrieving the kth
element. Which of the following statements about these array list operations is correct?
a) The most expensive operation of an array list is to add an element at the end.
b) The most expensive operation of an array list is to remove an element at the end.
c) The most expensive operation of an array list is to add an element in the middle.
d) The most expensive operation of an array list is to retrieve an arbitrary element.
Answer: c
61) Array list operations that were studied included adding/removing an element at the end or in the middle, and retrieving the kth
element. Which of the following statements about these array list operations is correct?
a) The least expensive operation of an array list is to add an element at the end.
b) The least expensive operation of an array list is to remove an element at the end.
c) The least expensive operation of an array list is to add an element in the middle.
d) The least expensive operation of an array list is to retrieve an arbitrary element.
Answer: d
62) Linked list operations that were studied included adding/removing an element at the end or in the middle, and retrieving the
kth element. If the iterator is currently pointing to the correct location for insertion or removal, which of the following statements
about these doubly-linked list operations is correct?
a) The most expensive operation of a doubly-linked list is to add an element at the end.
b) The most expensive operation of a doubly-linked list is to remove an element at the end.
c) The most expensive operation of a doubly-linked list is to add an element in the middle.
d) The most expensive operation of a doubly-linked list is to retrieve an arbitrary element.
Answer: d
63) Linked list operations that were studied included adding/removing an element at the end or in the middle, and retrieving the
kth element. If the iterator is currently pointing to the correct location for insertion or removal, which of the following statements
about these doubly-linked list operations is correct?
a) The least expensive operation of a doubly-linked list is to add an element at the end.
b) The least expensive operation of a doubly-linked list is to retrieve an arbitrary element.
c) The least expensive operation of a doubly-linked list is to add an element in the middle.
d) All of these operations have the same time cost.
Answer: c
64) Which operations from the array list data structure could be used in the implementation of the push and pop operations of a
stack data structure?
I addLast
II addFirst
III removeFirst
a) I
b) II
c) I and II
d) II and III
Answer: d
65) Which of the following operations from the array list data structure could be used in the implementation of the push and pop
operations of a stack data structure?
I addLast
II addFirst
III removeLast
a) I b) II
c) I and III d) II and III
Answer: b
Maha Otaibi 131
66) Complete the following code, which is intended to add an element to the top of a stack implemented as a linked list.
a)
first = newNode;
newNode.next = first;
b)
newNode.next = first;
first = newNode;
c)
newNode.previous = first;
first.next = newNode;
d)
first = newNode;
newNode.previous = first;
Answer: b
67) A stack can be implemented as a sequence of nodes in a linked list or an array list. Which of the following statements about
this is correct?
a) If implementing the stack as a linked list, the least expensive approach is to add and remove elements at the end.
b) If implementing the stack as an array list, the least expensive approach is to add and remove elements at the end.
c) If implementing the stack as an array list, there is no cost difference whether adding and removing elements at the beginning or
the end.
d) If implementing the stack as a linked list, there is no cost difference whether adding and removing elements at the beginning or
the end.
Answer: b
68) A stack can be implemented as a sequence of nodes in a linked list or an array list. Which of the following statements about
this is correct?
a) If implementing the stack as a linked list, it is more expensive to add and remove elements at the end than at the beginning.
b) If implementing the stack as an array list, it is more expensive to add and remove elements at the end than at the beginning.
c) If implementing the stack as an array list, there is no cost difference whether adding and removing elements at the beginning or
the end.
d) If implementing the stack as a linked list, there is no cost difference whether adding and removing elements at the beginning or
the end.
Answer: a
69) When implementing a queue as a singly-linked list, which of these statements is correct?
a) For better efficiency, nodes should be added at the back and removed at the front.
b) For better efficiency, nodes should be added at the front and removed at the back.
c) There is no difference in efficiency whether nodes are added at the front and removed at the back, or added at the back and
removed at the front.
d) You cannot effectively implement a queue as a singly-linked list.
Answer: a
70) You have implemented a queue as a singly-linked list, adding elements at the end and removing elements at the front. What is
the cost of the add operation?
a) O(log n)
b) O(n)
c) O(n2)
d) O(1)
Answer: d
71) You have implemented a queue as a singly-linked list, adding elements at the end and removing elements at the front. What is
the cost of the remove operation?
a) O(log(n))
b) O(n)
c) O(n2)
d) O(1)
Answer: d
public ArrayStack()
{
final int INITIAL_SIZE = 10;
elements = new Object[INITIAL_SIZE];
currentSize = 0;
}
a)
elements[currentSize] = element;
currentSize++;
b)
currentSize++;
elements[currentSize] = element;
c)
elements[currentSize - 1] = element;
currentSize++;
d)
elements[currentSize + 1] = element;
currentSize++;
Answer: a
73) Given the LinkedListStack class implementation discussed in section 16.3 (partially shown below), select the
statement(s) to complete the peek method.
public class LinkedListStack
{
private Node first;
public LinkedListStack()
{
first = null;
}
public LinkedListQueue()
{
first = null;
last = null;
}
75) Given the HashSet class implementation discussed in section 16.4 (partially shown below), select the statement needed to
complete the clear method, which is designed to remove all elements from the set.
public class HashSet
{
private Node[] buckets;
private int currentSize;
76) Elements in a hash table are said to ____ when they have the same hash code value.
a) be equivalent b) compress
c) collide d) buffer well
Answer: c
79) Which of the following statements about hash tables is NOT correct?
a) Each entry in a hash table points to a sequence of nodes whose elements have the same compressed hash code.
b) Elements with the same hash code are stored as nodes in a bucket associated with that hash code.
c) A compressed hash code is used as an array index into the hash table.
d) All elements of a hash table must be searched sequentially to determine if an element already exists.
Answer: d
80) Assume that you have a hash table in which there are few or no collisions. What is the time required to locate an element in
this hash table?
a) O(log n) b) O(n)
c) O(n2) d) O(1)
Answer: d
81) In the separate chaining technique for handling collisions in a hash table, ____.
a) colliding elements are stored in a nested hash table.
b) colliding elements are placed in empty locations in the hash table.
c) colliding elements are stored in linked lists associated with the hash code.
d) the hash code is compressed to obtain unique hash codes.
Answer: c
82) In the open addressing technique for handling collisions in a hash table, ____.
a) colliding elements are stored in a nested hash table.
b) colliding elements are placed in empty locations in the hash table.
c) colliding elements are stored in linked lists associated with the hash code.
d) the hash code is compressed to obtain unique hash codes.
Answer: b
83) Complete the following code snippet, which is intended to compress a hash code to become a valid array index:
int h = x.hashCode();
if (h < 0) { h = -h; }
_______________
a) position = arrayLength % h;
b) position = arrayLength / h;
c) position = h / arrayLength;
d) position = h % arrayLength;
Answer: d
84) Complete the following code snippet, which is intended to compress a hash code to become a valid array index:
_____________________
if (h < 0) { h = -h; }
position = h % arrayLength;
a) double h = x.hashCode();
b) double h = x.getHashCode();
c) int h = x.hashCode();
d) int h = x.getHashCode();
Answer: c
86) Consider the following code snippet, which computes h, the array index for storing x in a hash table.
int h = x.hashCode();
if (h < 0) { h = -h; }
h = h % size;
What does size correspond to?
a) The size of the hash table.
b) The number of elements to be stored.
c) The number of collisions.
d) The index of an empty hash table slot.
Answer: a
87) What technique is used to store elements that hash to the same location?
a) colliding
b) bucketing
c) deletion
d) sharing
Answer: b
88) Assume that you have a hash table in which there are few or no collisions. What is the time required to add a new element to
this hash table?
a) O(log(n))
b) O(n)
c) O(n2)
d) O(1)
Answer: d
89) Assume that you have a hash table in which there are few or no collisions. What is the time required to remove an element
from this hash table?
a) O(n)
b) O(n2)
c) O(1)
d) O(log (n))
Answer: c
90) Which of the following statements about adding an element to a hash table is NOT correct?
a) Add the new element at the beginning of the node sequence in the bucket referenced by the hash code.
b) Check the elements in the bucket to determine if the new element already exists.
c) If the element matches another element in the bucket referenced by the hash code, add the new element to that bucket.
d) To add an element, its compressed hash code must be computed.
Answer: c
91) If your hashCode function returns a number anywhere in the hash table with equal probability, what is the likely result?
a) Some objects will be impossible to find.
b) The number of collisions will be high.
c) The get method will run at O(n) complexity.
d) The get method will run at O(1) complexity.
Answer: d
92) Which hash table method(s) will make use of the equals method?
I put
II get
III contains
a) I
b) I and II
c) III
d) I, II and III
Answer: d
94) What is the time required to iterate over all elements in a hash table of size n?
a) O(log(n))
b) O(n)
c) O(n2)
d) O(1)
Answer: b
95) Assume that you have a hash table in which there are an average number of collisions. What is the time required to remove an
element from this hash table?
a) O(n)
b) O(n2)
c) O(1)
d) O(1)+
Answer: d
96) Assume that you have a hash table in which there are an average number of collisions. What is the time required to find an
element in this hash table?
a) O(n)
b) O(n2)
c) O(1)
d) O(1)+
Answer: c
97) Assume that you have a hash table in which there are an average number of collisions. What is the time required to add an
element to this hash table?
a) O(n)
b) O(n2)
c) O(1)
d) O(1)+
Answer: d
98) Complete the following code, which is intended to add an element to a hash table. Assume that the computed and compressed
hash code is stored in the variable h.
Node newNode = new Node();
newNode.data = x;
_________________
_________________
a)
newNode.next = buckets[h + 1];
buckets[h] = newNode;
b)
newNode.next = buckets[h];
buckets[h + 1] = newNode;
c)
newNode.next = buckets[h];
buckets[h - 1] = newNode;
d)
newNode.next = buckets[h];
buckets[h] = newNode;
Answer: d
99) What type of access does the use of an iterator provide for the elements of a bucket in a hash table?
a) sequential
b) semi-random
c) random
d) sorted
Answer: a
101) The ___ technique for handling collisions in a hash table with open addressing attempts to place colliding elements at the
next available location in the hash table.
a) sequential placement
b) sequential probing
c) linear placement
d) linear probing
Answer: d
102) Which statement about handling collisions in a hash table using the open addressing technique is correct?
a) A colliding element will always be contiguous to the location in which it would normally be placed.
b) To find an element, you must search from the hash code location until a match or an element with a different hash code is
found.
c) To remove an element, you simply empty the slot at which you find it.
d) There may be some elements with different hash codes that lie on the same probing sequence.
Answer: d
103) Which of the following statements about handling collisions in a hash table using the sequential chaining and open
addressing techniques is NOT correct?
a) The implementation of sequential chaining technique is simpler than the implementation of the open addressing technique.
b) The sequential chaining technique is simpler to understand than the open addressing technique.
c) The sequential chaining technique requires the storage of links while open addressing does not.
d) The sequential chaining technique requires less memory use than open addressing.
Answer: d
104) Which statement about handling collisions in a hash table using the open addressing technique is NOT correct?
a) A colliding element may not be contiguous to the location in which it would normally be placed.
b) To find an element, you must search from the hash code location until a match or an empty slot is found.
c) To remove an element, you simply empty the slot at which you find it.
d) There may be some elements with different hash codes that lie on the same probing sequence.
Answer: c