Programming II Final Review 3

Ace your homework & exams now with Quizwiz!

Insert the missing code in the following segment. The code intends to get the newly selected item from the combo box. JComboBox facenameCombo = new JComboBox(); String selectedString = __________________________; (String) facenameCombo.getSelected(); (String) facenameCombo.getSelectedItem(); (String) selectedString.getSelected(); (String) selectedString.getSelectedItem();

(String) facenameCombo.getSelectedItem();

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<>(); // code to add elements to the linked list if ______________________________________ { System.out.print(name + " is the first player on the list."); } (players.getFirst().equals(name)) (players[0].equals(name)) (players.contains(name)) (players.indexOf(name) == 1)

(players.getFirst().equals(name))

Given the following code snippet for searching an array: int[] arr = {23, 25, 29, 34, 42}; int newVal = 15; int pos = Arrays.binarySearch(arr, newVal); What value will pos have when this code is executed? 0 1 -2 -1

-1

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(); -7 24 24 24 -7 -7 24 -7

-7 24

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. 3 2 4 1

2

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 long will it take the computer to sort 1,024 times that many, or 1,048,576 elements? 8,192x 1,024x 2,048x 1,048,576x

2,048x

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? 1,2,4,3 4,3,2,1 4,3,1,2 1,2,3,4

4,3,2,1

When you use a timer, you need to define a class that implements the ____ interface. TimerListener TimerActionListener ActionListener StartTimerListener

ActionListener

When using a list iterator, on which condition will the IllegalStateException be thrown? Calling next after calling previous. Calling remove after calling previous. Calling remove after calling remove. Calling remove after calling next.

Calling remove after calling remove.

Which of the following is true about a border layout? It groups components into three areas: center, north, and south It is the default manager for JPanel Each area can hold a single component, or it can be empty Components do not expand to fill in the space of the border layout

Each area can hold a single component, or it can be empty

____ are generated when the user presses a key, clicks a button, or selects a menu item. Errors Interfaces Events Listeners

Events

Suppose a JPanel with a BorderLayout manager contains two components: component1, which was added to the EAST, and component2, which was added to the WEST. Which parts of the JPanel appear? I North II South III Center IV West V East

III, IV, and V

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? Its running time will be O(n log (n)). Its running time will be O(n2). Its running time will be O(n). You Answered Its running time will be O(log (n)).

Its running time will be O(n).

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? Vehicle myAuto = new Auto("sedan"); LandVehicle myAuto = new Auto("sedan"); Auto myAuto = new Auto("sedan"); LandVehicle myAuto = new Vehicle("sedan");

LandVehicle myAuto = new Vehicle("sedan");

Select an expression to complete the program segment below, which displays an error message and terminates normally if the String variable accountNumber does not contain an integer value. try { int number = Integer.parseInt(accountNumber); } catch ( ________________________ ) { System.out.println("Account number is not an integer value"); } NumberFormatException exception InputMismatchException exception ArithmeticException exception IOException exception

NumberFormatException exception

An algorithm that tests whether the first array element is equal to any of the other array elements would be an ____ algorithm. O(n log (n)) O(log (n)) O(1) O(n)

O(n)

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? The strings are the identical. We can only conclude the strings are of the same length. One string is the reverse of the other. The strings are different.

One string is the reverse of the other.

What is the easiest way to create complex-looking GUI layouts? I use the GridBagLayout manager II nest panels, each with its own layout manager III use multiple layout managers in the same container

Only II

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

Which of the following correctly declares a stack that will hold String elements? Stack s = new Stack<>(); Stack<String> s = new Stack<>(); String s = new Stack(); String s = new Stack<>();

Stack<String> s = new Stack<>();

Which of the following statements about exception handling is correct? Statements that may cause an exception should be placed within a catch block. Statements that may cause an exception should be placed within a try block. The main method of a Java program will handle any error encountered in the program. Statements that may cause an exception should be placed within a throws block.

Statements that may cause an exception should be placed within a try block.

What is a class called that represents the most general entity in an inheritance hierarchy? Default class. Superclass. Subclass. Inheritance class.

Superclass.

The _______ interface toolkit has a large set of user-interface components. GUI Builder graphical user Swing JMenu

Swing

Consider the following code snippet: public class Motorcycle extends Vehicle { . . . public Motorcycle(int numberAxles) { super(numberAxles); //line #1 } } If the line marked "//line #1" was missing, which of these statements would be correct? The Vehicle class constructor would invoke the constructor of the Motorcycle class with no parameters. The Motorcycle class constructor would invoke the constructor of the Vehicle class with a parameter value of 0. The Motorcycle class constructor would invoke the constructor of the Vehicle class with no parameters. This code would not compile.

The Motorcycle class constructor would invoke the constructor of the Vehicle class with no parameters.

What does the MouseAdapter class provide? A class can implement the MouseAdapter class to handle mouse events. The MouseAdapter class allows your program to accept input from multiple mice. The MouseAdapter class implements all of the methods of the MouseListenerinterface as do-nothing methods, eliminating the need to provide an implementation for all 5 methods of the MouseListener interface. The MouseAdapter class implements all of the methods of the ActionListenerinterface as do-nothing methods, eliminating the need to implement the ActionListener interface.

The MouseAdapter class implements all of the methods of the MouseListenerinterface as do-nothing methods, eliminating the need to provide an implementation for all 5 methods of the MouseListener interface.

Assume a class implements two interfaces, both of which define a default method with the same signature. Which statement is true about this conflict of inherited methods? The code compiles but generates an exception at run time due to the conflict. The code compiles and the implementation is chosen at run time. The class must override the method and provide its own implementation. There is no conflict because interfaces cannot provide method implementation.

The class must override the method and provide its own implementation.

Using the given definition of the Measurable interface: public interface Measurable { double getMeasure(); } Consider the following code snippet, assuming that BankAccount has a getBalance method and implements the Measurable interface by providing an implementation for the getMeasure method: Measurable m = new BankAccount(); System.out.println(m.getBalance()); Which of the following statements is true? The code does not compile because a variable of type Measurable does not have a getBalance method. The code compiles but generates an exception at run time because a Measurableobject reference does not have a getBalance method. The code executes, displaying the balance of the bank account. The code does not compile because you cannot assign a BankAccount object to a variable of type Measurable.

The code does not compile because a variable of type Measurable does not have a getBalance method.

When a program throws an exception within a method that has no try-catch block, which of the following statements about exception handling is true? The user must decide whether to continue or terminate the program. The current method must decide whether to continue or terminate. The current method terminates immediately. Execution will continue with the next statement in the method.

The current method terminates immediately.

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? The current third and fourth nodes. The current fourth and fifth nodes. The current first node. The current third node.

The current third and fourth nodes.

Consider the sort method shown below for selection sort: public static void sort(int[] a) { for (int i = 0; i < a.length - 1; i++) { int minPos = minimumPosition(i); swap(minPos, i); } } Suppose we modify the loop condition to read i < a.length. What would be the result? The sort would work exactly the same as before the code modification. The sort would work, but run one more iteration. The sort would work but with one less iteration. An exception would occur.

The sort would work, but run one more iteration.

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? They are all less than or equal to the pivot element. They are all greater than or equal to the pivot element. They are all sorted. None can equal the pivot element.

They are all less than or equal to the pivot element.

Consider the following code snippet: throw new IllegalArgumentException("This operation is not allowed!"); Which of the following statements about this code is correct? This code throws an existing IllegalArgumentException object. This code will not compile. This code constructs an object of type IllegalArgumentException and throws the object. This code constructs an object of type IllegalArgumentException and reserves it for future use.

This code constructs an object of type IllegalArgumentException and throws the object.

Consider the following code snippet: File inputFile = new File(filename); try (Scanner in = new Scanner(inputFile)) { . . . } catch (Exception e) { } Which of the following statements about this code is correct? This code will not catch a FileNotFoundException that occurs in the try block. This code will not catch any exceptions that occur in the try block. This code will pass any exceptions back to its caller. This code will catch exceptions that occur in the try block but will do nothing about the exceptions.

This code will catch exceptions that occur in the try block but will do nothing about the exceptions.

Consider the following code snippet: public class Motorcycle extends Vehicle { private String model; . . . public Motorcycle(int numberAxles, String modelName) { model = modelName; super(numberAxles); } } What does this code do? It invokes the constructor of the Vehicle class from within the constructor of the Motorcycle class. It invokes the constructor of the Motorcycle class from within the constructor of the Vehicle class. It invokes a private method of the Vehicle class from within a method of the Motorcycle class. This code will not compile.

This code will not compile.

Consider the following code snippet: throw IllegalArgumentException("This operation is not allowed!"); Which of the following statements about this code is correct? This code constructs an object of type IllegalArgumentException and throws the object. This code throws an existing IllegalArgumentException object. This code constructs an object of type IllegalArgumentException and reserves it for future use. This code will not compile.

This code will not compile.

Which of the following statements about manipulating objects in a map is NOT correct? Use the remove method to remove a value from the map. Use the get method to retrieve a value from the map. Use the keyset method to get the set of keys for the map. Use the add method to add a new element to the map.

Use the add method to add a new element to the map.

What is wrong with the following code? class ExitListener implements ActionListener { public void actionPerformed(ActionEvent event) { System.exit(0); } } ActionListener exitListener = new ExitListener(); JMenu exitMenu = new JMenu("Exit"); exitMenu.addActionListener(exitListener); JMenuBar menuBar = new JMenuBar(); menuBar.add(exitMenu); The ExitListener class is not public You cannot attach a listener to a menu, only to a menu item You cannot add a menu to the menu bar, only a menu item You need to use a menu listener, not an action listener

You cannot attach a listener to a menu, only to a menu item

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.compareTo(b) == -1 a.compareTo(b) < 0 a.compareTo(b) == 0 a.compareTo(b) > 0

a.compareTo(b) < 0

When adding a component to a container with the ____ layout, specify the NORTH, EAST, SOUTH, WEST, or CENTER position. border grid grid bag flow

border

Insert the missing code in the following code fragment. This fragment is intended to allow the user to select a file to be opened. JFileChooser chooser = new JFileChooser(); Scanner in = null; if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) { File selectedFile = __________; in = new Scanner(selectedFile); . . . } chooser.getFileName() chooser.getSelectedFileName() chooser.getSelectedFile() chooser.getFilePath()

chooser.getSelectedFile()

Which of the following is the correct class header for a MouseClickListener class that wants to take advantage of the do-nothing methods provided by the MouseAdapter class? class MouseClickListener implements MouseAdapter class MouseClickListener extends MouseAdapter interface MouseClickListener extends MouseAdapter class MouseClickListener implements MouseListener

class MouseClickListener extends MouseAdapter

The nodes of a(n) ____ linked list class store two links: one to the next element and one to the previous one. array singly randomly doubly

doubly

A binary search is generally ____ a linear search. faster than less efficient than slower than equal to

faster than

You wish to use the Scanner class's nextInt() method to read in whole numbers. To avoid exceptions that would occur if the input is not a whole number, you should use the ____ method before calling nextInt(). hasNextInteger() hasNext() hasNextInt() hasIntegerValue()

hasNextInt()

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; } if (a[i] > a[minPos]) { minPos = i; } if (a[i] < a[j]) { minPos = i; } if (a[i] < a[minPos]) { minPos = i; } if (a[i] < a[minPos]) { i = minPos; }

if (a[i] < a[minPos]) { minPos = i; }

To create a TreeSet for a class of objects, the object class must ____. implement the Set interface. implement the Comparable interface. create an iterator. create a Comparator object.

implement the Comparable interface.

Insert the missing code in the following code fragment. This fragment is intended to read all words from a text file named dataIn.txt. File inputFile = new File("dataIn.txt"); Scanner in = new Scanner(inputFile); while (____________) { String input = in.next(); System.out.println(input); } in.getNext() in.nextWord() in.hasNext() in.peek()

in.hasNext()

Event listeners are often installed as ____ classes so that they can have access to the surrounding fields, methods, and final variables. interface helper inner abstract

inner

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? java.swing.event.ActionEvent;. javax.awt.event.ActionEvent; java.awt.event.ActionEvent; javax.swing.event.ActionEvent;

java.awt.event.ActionEvent;

Assuming that the ClickListener class implements the ActionListenerinterface, what statement should be used to complete the following code segment? ClickListener listener = new ClickListener(); JButton myButton = new JButton("Submit"); JPanel myPanel = new JPanel(); myPanel.add(myButton); ______________________ //missing statement myButton.addActionListener(listener); myPanel.addActionListener(myButton); myPanel.addActionListener(listener); myButton.addActionListener(ClickListener);

myButton.addActionListener(listener);

Assume that you have declared a set named mySet to hold String elements. Which of the following statements will correctly delete an element from mySet? mySet.delete("apple"); mySet.remove("apple"); mySet.get("apple"); mySet.pop("apple");

mySet.remove("apple");

Insert the missing code in the following code fragment. This fragment is intended to read an input file named dataIn.txt and write to an output file named dataOut.txt. public static void main(String[] args) throws FileNotFoundException { String inputFileName = "dataIn.txt"; String outputFileName = "dataOut.txt"; File inputFile = _________________; Scanner in = new Scanner(inputFile); . . . } new File(inputFile) new File(System.in) new File(outputFileName) new File(inputFileName)

new File(inputFileName)

What is the term used for a subclass that defines a method with the same name as a method in its superclass, but with different parameter types? implementing inheriting overriding overloading

overloading

Based on the statement below, which of the following adds a title to the border? JPanel panel = new JPanel(); panel.setBorder(new TitledBorder()); panel.setBorder(new TitledBorder(new EtchedBorder(), "Size")); panel.setBorder(new TitledBorder(new EtchedBorder())); panel.setTitle("Size");

panel.setBorder(new TitledBorder(new EtchedBorder(), "Size"));

The term ____ is used in computer science to describe an access pattern in which the elements are accessed in arbitrary order. sequential access sorted access arbitrary access random access

random access

A list is a collection that ____. does not allow elements to be inserted in any position. only allows items to be added at one end and removed at the other end. manages associations between keys and values. should be used when you need to remember the order of elements in the collection.

should be used when you need to remember the order of elements in the collection.

An Undo feature in a word processor program that allows you to reverse a previously completed command is probably implemented using which structure type? stack queue hash table linked list

stack

Consider the following code snippet: public interface Measurable { double getMeasure(); ____________ double sum(Measurable[] objects) { // implementation to compute the sum of the Measurable objects } } Which of the following completes the interface declaration correctly? final private static public

static

If a subclass defines the same method name and the same parameter types for a method that appears in its superclass, which statement is true? the subclass method overloads the superclass method. the subclass method overrides the superclass method. the subclass has implemented the method on behalf of the superclass. a compiler error will occur.

the subclass method overrides the superclass method.

Suppose the abstract class Message is defined below public abstract class Message { private String value; public Message(String initial) { value = initial; } public String getMessage() { return value; } public abstract String translate(); } A concrete subclass of Message, called FrenchMessage, is defined. Which methods must FrenchMessage define? translate() only getMessage() only The FrenchMessage constructor and translate() only The FrenchMessage constructor, getMessage(), and translate()

translate() only

Consider the following code snippet: public class MyMouseListener { public void mousePressed(MouseEvent event) { double x; double y; _______ System.out.println("x: " + x + ", y: " + y); } } Which of the following statements should be in the indicated position to print out where the mouse was pressed? x = event.printX(); y = event.printY(); x = (MouseEvent) getX(); y = (MouseEvent) getY(); x = event.getX(); y = event.getY(); x = event.getXposition(); y = event.getYposition();

x = event.getX(); y = event.getY();


Related study sets

PA Property & Casualty Insurance Exam (C)

View Set

8 Antibacterial Drugs That Interfere With Protein Synthesis

View Set

Solutions Exam: Multiple Choice and Math

View Set

Genetica - Capitolo 1: struttura e funzione del DNA

View Set

Chapter 5: Consumer Credit: Advantages, Disadvantages, Sources, and Costs

View Set

CHAPTER 1: The Role of Marketing Research (MKT 455)

View Set