Programming II Final Review 1
17) Which of the following correctly completes the Java statement shown to add a listener to a button using a lambda expression? button.addActionListener(_________________________________); A. (ActionEvent event) => System.out.println("Clicked!") B. lambda((ActionEvent event) -> System.out.println("Clicked!")) C. (ActionEvent event) -> System.out.println("Clicked!") D. lambda(ActionEvent event, System.out.println("Clicked!"))
(ActionEvent event) -> System.out.println("Clicked!")
47) 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 = 1; j <= 200; j++) B. (int j = 1; j < k; j = j * 2) C. (int j = 0; j < k; j++) D. (int j = n; j > 0; j = j / 2)
(int j = 0; j < k; j++)
65) Select an appropriate expression to complete the following code segment, which is designed to print a message if the string stored in name is part of the players collection. Collection<String> players = new ArrayList<>(); // code to add elements to the collection here if ______________________________________ { System.out.print(name + " is one of the players in the collection."); } A. (players.contains(name)) B. (players.indexOf(name)) C. (players.search(name)) D. (players.equals(name))
(players.contains(name))
6) Consider the classes shown below: public class Parent { public int getValue() { return 24; } public void display() { System.out.print(getValue() + " "); } } public class Child extends Parent { public int getValue() { return -7; } } Using the classes above, what is the output of the following lines of code? Parent kid = new Child(); Parent adult = new Parent(); kid.display(); adult.display(); A. -7 24 B. 24 24 C. -7 -7 D. 24 -7
-7 24
52) When the size of an array increases by a factor of 100, the time required by selection sort increases by a factor of ____. A. 5,000 B. 10,000 C. 12,000 D. 2,000
10,000
48) 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. 16 B. 30 C. 20 D. 1
20
45) What is the smallest value of n for which n2> 3n + 4? A. 6 B. 5 C. 4 D. 3
5
25) Which of the following statements about using a PrintWriter object is NOT true? A. PrintWriter is an enhancement of the PrintStream class. B. A program can write to a PrintWriter using println. C. A PrintWriter will be automatically closed when the program exits. D. Data loss may occur if a program fails to close a PrintWriter object before exiting.
A PrintWriter will be automatically closed when the program exits.
9) Which of the following is true regarding inheritance? A. When creating a subclass, all methods of the superclass must be overridden. B. When creating a subclass, no methods of a superclass can be overridden. C. A superclass can force a programmer to override a method in any subclass created from it. D. A superclass cannot prevent a programmer from overriding a method in any subclass created from it.
A superclass can force a programmer to override a method in any subclass created from it.
69) When the user selects a menu item, the menu item sends a(n) ___________________. A. ActionEvent B. ChangeEvent C. ItemEvent D. MouseEvent
ActionEvent
67) How do you add two buttons to the south area of a frame using the BorderLayout? A. Add them to a panel, then add the panel to the SOUTH B. Add one to the SOUTH, then add the second one to the SOUTH C. Add one to the SOUTH, then add the second one to the CENTER D. Add one to the CENTER, then add the second one to the SOUTH
Add them to a panel, then add the panel to the SOUTH
21) Which of the following statements about an inner class is true? A. An inner class is used for a utility class that should be visible elsewhere in the program. B. An inner class that is defined inside a method is publicly accessible. C. An inner class that is defined inside a method is not publicly accessible. D. An inner class that is defined inside an enclosing class but outside of its methods is not available to all methods of the enclosing class.
An inner class that is defined inside a method is not publicly accessible.
68) The code below will not compile successfully unless the argument to the makeMenuItem method is final. Why not? public JMenuItem makeMenuItem(final String menuLabel) { JMenuItem mi = new JMenuItem(menuLabel); class MyMenuListener implements ActionListener { public void actionPerformed(ActionEvent e) { doSomethingElse(); System.out.println(menuLabel); } } mi.addActionListener(new MyMenuListener()); return mi; } A. JMenuItem labels must be final B. This prevents the menuLabel argument from being modified C. Because a local variable is being accessed from an inner classes D. Because the String class is final
Because a local variable is being accessed from an inner classes
28) Which expression converts the string input containing floating-point digits to its floating-point value? A. input.parseFloat() B. input.parseDouble() C. Double.parseDouble(input) D. Float.parseFloat(input)
Float.parseFloat(input)
71) What is the default layout manager of JPanel? A. FlowLayout B. GridLayout C. BoxLayout D. GridBagLayout
FlowLayout
42) 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
I and II only
39) 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
I only
66) Which elements of creating a graphical user interface are made easier by a GUI builder? I creating event handlers II configuring component properties III adding components
I, II, and III
58) 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
II and III
46) When does quicksort's worst-case run-time behavior occur? I when the data is randomly initialized in the array II when the data is in ascending order III when the data is in descending order
II and III only
26) Which exception class should you use from the standard library if you want to thrown an exception when there are insufficient funds in a bank account to cover a withdrawal? A. OutOfBoundsException B. RunTimeException C. IOException D. IllegalArgumentException
IllegalArgumentException
31) In the hierarchy of Exception classes, the NumberFormatException class is a subclass of the ____ class. A. ClassCastException B. IllegalStateException C. IllegalArgumentException D. ArithmeticException
IllegalArgumentException
54) 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? A. It number of visits goes up by a factor of eight. B. It triples the number of visits. C. It quadruples the number of visits. D. It doubles the number of visits.
It number of visits goes up by a factor of eight.
51) A portion of your program includes the method shown in the code snippet below to examine the elements of an array arr: private int findElement(int[] arr, int newVal) { int pos = Arrays.binarySearch(arr, newVal); return pos; } What can you conclude about the running time of this section of code? A. Its running time will be O(log (n)). B. Its running time will be O(n). C. Its running time will be O(n log (n)). D. Its running time will be O(n2).
Its running time will be O(log (n)).
24) Which of the following statements about character encodings is NOT true? A. It is recommended to specify the UTF-8 encoding when processing files with special symbols or characters in multiple languages. B. Java assumes the UTF-8 encoding. C. A character is encoded as a sequence of bytes, each having a value between 0 and 255. D. Java supports the reading and writing of files in the UTF-8 encoding.
Java assumes the UTF-8 encoding
18) Which of the following statements about lambda expressions is NOT true? A. Lambda expressions are used to define a single function of a functional interface. B. A lambda expression defines the parameters and return value of a method in a compact notation. C. Lambda expressions are a convenient notation for callbacks. D. Lambda expressions cannot contain a method body enclosed in braces with a return statement.
Lambda expressions cannot contain a method body enclosed in braces with a return statement.
7) All hamsters are rodents and all rodents are mammals. What hierarchy best captures this information? A. Hamster is a superclass of Rodent and Rodent is a superclass of Mammal B. Mammal is a superclass of Rodent and Rodent is a superclass of Hamster C. Mammal is a superclass of Rodent and Hamster D. Hamster is a superclass of Rodent and Mammal
Mammal is a superclass of Rodent and Rodent is a superclass of Hamster
10) What must a subclass method do in order to override a superclass method? A. Must use a different method name. B. Must use the same method name and the same parameter types. C. Must use a different method name and the same parameter types. D. Must use a different method name and different parameter types.
Must use the same method name and the same parameter types.
75) What type does the method getSelectedItem in the JComboBox classreturn? A. Object B. String C. JRadioButton D. JLabel
Object
14) Consider the following declarations: public interface Measurer { int measure(Object anObject); } public class StringLengthMeasurer implements Measurer { public int measure(_________________) { String str = (String) anObject; return str.length(); } } What parameter declaration can be used to complete the callback measure method? A. String aString B. Object aString C. Object anObject D. String anObject
Object anObject
73) Which layout manager uses a grid, but allows selected grid locations to span multiple rows or columns? I GridBagLayout II BorderLayout III GridLayout
Only I
70) Which layout manager allows you to add components in different orders, with the result being the same GUI appearance? I FlowLayout II BorderLayout III GridLayout
Only II
57) Which of the following algorithms would be efficiently executed using a LinkedList? A. Remove first n/ 2 elements from a list of n elements. B. Read n / 2 elements in random order from a list of n elements. C. Tracking paths in a maze. D. Binary search.
Remove first n/ 2 elements from a list of n elements.
29) Consider the following code snippet: File inputFile = new File("input.txt"); You wish to read the contents of this file using a Scanner object. Which of the following is the correct syntax for doing this? A. Scanner in = new Scanner("input.txt"); B. Scanner in = new Scanner(inputFile); C. Scanner in = Scanner.open(inputFile); D. Scanner in = Scanner("input.txt");
Scanner in = new Scanner(inputFile);
56) 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<>(); . . . _______________________________ for (String aKey : mapKeySet) { String name = myMap.get(aKey); System.out.println("ID: " + aKey + "->" + name); } A. Map<String, String> mapKeySet = myMap.keySet(); B. Set<String, String> mapKeySet = myMap.keySet(); C. Set<String> mapKeySet = myMap.keySet(); D. Set<String> mapKeySet = myMap.getKeySet();
Set<String> mapKeySet = myMap.keySet();
53) 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? private static void swap(int[] a, int i, int j) { int temp = a[i]; a[i] = a[j]; a[j] = temp; } private static void swap2(int[] a, int i, int j) { a[i] = a[j]; a[j] = a[i]; } A. Some array elements would be overwritten. B. It would sort the array in reverse order. C. It would still be correct, but run a little faster. D. There would be no effect.
Some array elements would be overwritten.
1) Consider the following code snippet: public class Vehicle { . . . public void setVehicleClass(double numberAxles) { . . . } } public class Motorcycle extends Vehicle { . . . public void setVehicleClass(double numberAxles) { . . . } } Which of the following statements is correct? 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.
The Motorcycle class's setVehicleClass method overrides the Vehicle class's setVehicleClass method.
11) In Java, if you define two methods that have the same but different parameter types, the compiler will not complain. Why not? A. The compiler will use only the most recent method definition. B. The compiler considers the two methods to be completely unrelated. C. The compiler cannot detect the difference between the two methods. D. The compiler will silently link the two methods through inheritance.
The compiler considers the two methods to be completely unrelated.
20) 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? A. button should be declared as final B. There is no error. C. The listener cannot access the methods of the myOrder object. D. The listener has not been attached to the button.
The listener has not been attached to the button.
44) When using the add method of the ListIterator to add an element to a linked list, which of the following statements is correct? A. The new element is inserted before the iterator position, and a subsequent call to next would be unaffected. B. The new element is inserted after the iterator position, and a subsequent call to next would return the new element. C. The new element is inserted after the iterator position, and a subsequent call to previous would be unaffected. D. The new element is inserted before the iterator position, and a subsequent call to next would return the new element.
The new element is inserted before the iterator position, and a subsequent call to next would be unaffected.
72) Which of the following is false about achieving complex layouts? A. By giving each panel an appropriate layout manager, the panels can be nested B. There are more complex layout managers such as the grid bag layout and group layout C. You can use as many panels as you need to organize your components D. The order of the nested panel does not matter
The order of the nested panel does not matter
27) Consider the following code snippet. Scanner inputFile = new Scanner("hoursWorked.txt"); Which of the following statements is correct? A. This code will open an existing file named "hoursWorked.txt" for reading. B. This code will create a new file named "hoursWorked.txt". C. This code will treat the string "hoursWorked.txt" as an input value. D. This code will open a file named "hoursWorked.txt" for writing.
This code will treat the string "hoursWorked.txt" as an input value.
30) Consider the following code snippet, where data is a variable defined as a double array that is populated by the readData method for valid data: public double[] readInputFile(String filename) throws IOException { try (Scanner in = new Scanner(new File(filename))) { readData(in); return data; } } Which of the following statements about this method's code is correct? A. Any exceptions that occur in this method will be suppressed. B. This method will pass any IOException-type exception back to the caller. C. The method will never close the file if an IOException exception occurs in this method. D. This method will pass any type of exception back to the caller.
This method will pass any IOException-type exception back to the caller.
63) You need to access values using a key, and the keys must be sorted. Which collection type should you use? A. Queue B. TreeMap C. HashMap D. ArrayList
TreeMap
2) Consider the following class hierarchy: public class Vehicle { private String type; public Vehicle(String type) { this.type = type; System.out.print("Vehicle "); } public String displayInfo() { return type; } } public class LandVehicle extends Vehicle { public LandVehicle(String type) { super(type); System.out.print("Land "); } } public class Auto extends LandVehicle { public Auto(String type) { super(type); System.out.print("Auto "); } } When an object of type Vehicle is constructed, what will be printed by the constructors from this inheritance hierarchy? A. Vehicle Land Auto B. Auto Land Vehicle C. Vehicle D. Auto
Vehicle
8) Which of the following statements about classes is true? 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.
You can create an object from a concrete class, but not from an abstract class.
19) You have a class that extends the JComponent class. In this class you have created a painted graphical object. Your code will change the data in the graphical object. What additional code is needed to ensure that the graphical object will be updated with the changed data? A. You must call the component object's paintComponent() method. B. You must call the component object's repaint() method. C. You do not have to do anything - the component object will be automatically repainted when its data changes. D. You must use a Timer object to cause the component object to be updated.
You must call the component object's repaint() method
64) Consider the following code snippet: Queue<String> stringQueue = new LinkedList<>(); stringQueue.add("ab"); stringQueue.add("abc"); stringQueue.add("a"); while (stringQueue.size() > 0) { System.out.print(stringQueue.remove() + ","); } What output will be produced when this code is executed? A. ab,abc,a, B. abc,ab,a, C. a,abc,ab, D. a,ab,abc,
ab,abc,a,
16) A method that has no implementation is called a/an ____ method. A. abstract B. overloaded C. interface D. implementation
abstract
35) Consider the following code snippet: LinkedList<String> words = new LinkedList<>(); words.addFirst("abc"); words.addLast("def"); words.addFirst("ghi"); System.out.print(words.removeLast()); System.out.print(words.removeFirst()); System.out.print(words.removeLast()); What will this code print when it is executed? A. ghiabcdef B. defghiabc C. abcdefghi D. abcghidef
defghiabc
62) Consider the following code snippet: LinkedList<String> words = new LinkedList<>(); words.addFirst("abc"); words.addLast("def"); words.addFirst("ghi"); System.out.print(words.removeLast()); System.out.print(words.removeFirst()); System.out.print(words.removeLast()); What will this code print when it is executed? A. ghiabcdef B. defghiabc C. abcdefghi D. abcghidef
defghiabc
36) Consider the following code snippet: LinkedList<String> words = new LinkedList<>(); words.addLast("abc"); words.addLast("def"); words.addLast("ghi"); System.out.print(words.removeLast()); System.out.print(words.removeFirst()); System.out.print(words.removeLast()); What will this code print when it is executed? A. abcdefghi B. defghiabc C. ghiabcdef D. abcghidef
ghiabcdef
41) Which method is NOT part of the ListIterator interface? A. hasPrevious B. hasMore C. add D. hasNext
hasMore
49) Consider the following code snippet: public static void sort(int[] a) { for (int i = 1; i < a.length; i++) { int next = a[i]; int j = i; while (j > 0 && a[j - 1] > next) { a[j] = a[j - 1]; j--; } a[j] = next; } } What sort algorithm is used in this code? A. quicksort B. insertion sort C. merge sort D. selection sort
insertion sort
3) Why is the following code, which assumes ChoiceQuestion is a subclass of Question, considered poor strategy? if (q instanceof ChoiceQuestion) { // Do the task the ChoiceQuestion way } else if (q instanceof Question) { // Do the task the Question way } A. Question should be the subclass, not the other way around. B. instanceof is not an operator but rather a method. C. instanceof should not be used for type tests that can be solved by using polymorphism. D. the instanceof reserved word should only be used in a class constructor.
instanceof should not be used for type tests that can be solved by using polymorphism.
50) 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. closer to its correct final location B. lowest index in array still available C. its final correct location D. highest index in array still available
its final correct location
15) If the user presses and releases a mouse button in quick succession without moving the mouse, which methods of the MouseListener interface are called? A. Only the mouseDblClicked method. B. mousePressed, mouseReleased, and mouseClicked. C. mousePressed, mouseReleased, and mouseDblClicked D. Only the mouseClicked method.
mousePressed, mouseReleased, and mouseClicked.
13) To build a user interface that contains graphical components, the components ____. A. must each be added to a separate panel. B. must be added directly to a frame component. C. must be added to a panel that is contained within a frame. D. must be added to a frame that is contained within a panel.
must be added to a panel that is contained within a frame.
5) Consider the following class hierarchy: public class Vehicle { private String type; public Vehicle(String type) { this.type = type; } public String displayInfo() { return type; } } public class LandVehicle extends Vehicle { public LandVehicle(String type) { super(type); } } public class Auto extends LandVehicle { public Auto(String type) { super(type); } } You have written a program to use these classes, as shown in the following code snippet: public class VehicleTester { public static void main(String[] args) { Auto myAuto = new Auto("sedan"); System.out.println("MyAuto type = " + ______); } } Complete the code in this program snippet to correctly display the auto's type. 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.
myAuto.displayInfo()
37) 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.delete(); B. myStack.pop(); C. myStack.remove(); D. myStack.get();
myStack.pop();
32) Insert the missing code in the following code fragment. This fragment is intended to read a file named dataIn.txt and write to a file named dataOut.txt. public static void main(String[] args) throws FileNotFoundException { String inputFileName = "dataIn.txt"; String outputFileName = "dataOut.txt"; File inputFile = new File(inputFileName); Scanner in = new Scanner(inputFile); PrintWriter out = _____________; . . . } A. new PrintWriter(outputFile) B. new PrintWriter(outputFileName) C. new Scanner(outputFile) D. new Scanner(outputFileName)
new PrintWriter(outputFileName)
4) With a few exceptions, what access should instance variables of classes always have? A. final B. private C. public D. protected
private
33) Your program must read in an existing text file. You want the program to terminate if any exception related to the file occurs. Which of the following indicates the correct code for the header of the main method? A. public static void main(String[] args) throws FileNotFoundException B. public static void main(String[] args) C. public static void main(String[] args) throws IOException D. public static void main(String[] args) throws UnknownFileException
public static void main(String[] args) throws IOException
22) Consider the following class: public class ClickListener implements ActionListener { __________________________________________ { System.out.println("button event ..."); } } Which of the following method headers should be used to complete the ClickListener class? A. public void actionPerformed(ActionEvent event) B. public void actionPerformed(ClickListener event) C. public void actionPerformed() D. public void actionPerformed(ActionListener event)
public void actionPerformed(ActionEvent event)
40) Print jobs submitted to a printer would probably be stored in which type of data structure? A. linked list B. queue C. stack D. hash table
queue
43) 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. queue B. map C. stack D. linked list
queue
61) 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. queue B. map C. stack D. linked list
queue
60) A queue is a collection that ____. A. remembers the order of elements, and allows elements to be added and removed only at one end. B. remembers the order of elements and allows elements to be inserted only at one end and removed only at the other end. C. does not remember the order of elements but allows elements to be added in any position. D. remembers the order of elements and allows elements to be inserted in any position.
remembers the order of elements and allows elements to be inserted only at one end and removed only at the other end.
12) Consider the following class: public class BowlingGame implements Comparable { private int score; // other methods go here public int compareTo(Object otherObject) { BowlingGame otherGame = (BowlingGame) otherObject; __________________________________; } } What statement can be used to complete the compareTo() method? A. otherGame.score - score B. return (otherGame.score - score) C. score - otherGame.score D. return (score - otherGame.score)
return (score - otherGame.score)
38) Consider the following code snippet: Map<String, Integer> scores; You expect to retrieve elements randomly by key, and want fastest retrieval times. Which of the following statements will create a structure to support this? A. scores = new HashMap<>; B. scores = new Map<>; C. scores = new TreeMap<>; D. scores = new TreeSet<>;
scores = new HashMap<>;
34) A linear search only requires ____ access. A. sorted B. arbitrary C. sequential D. random
sequential
59) A linear search only requires ____ access. A. sorted B. arbitrary C. sequential D. random
sequential
74) What method is required by the ChangeListener interface? A. changeOccured B. actionPerformed C. stateChanged D. sliderMoved
stateChanged
23) Complete the code fragment below, which is designed to throw an exception if String variable accountNumber has more than seven characters. if (accountNumber.length() > 7) { ___________________________________________ } A. throws new IllegalArgumentException("Account number exceeds maximum length"); B. throw new IllegalArgumentException("Account number exceeds maximum length"); C. throws IllegalArgumentException("Account number exceeds maximum length"); D. throw IllegalArgumentException("Account number exceeds maximum length");
throw new IllegalArgumentException("Account number exceeds maximum length");
55) Choose the order of the following growth rates, from slowest to fastest: θ(n^3), θ(nlog(n)), θ(n^3/2), θ(2n). A. θ(n log(n)), θ(n3/2), θ(n3), θ(2n) B. θ(n3), θ(n log(n)), θ(n3/2), θ(2n) C. θ(n3/2), θ(n log(n)), θ(n3), θ(2n) D. θ(2n), θ(n3), θ(n3/2), θ(n log(n))
θ(n log(n)), θ(n3/2), θ(n3), θ(2