COP3337 Final Exam Notes

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

Which of the following defines the job of a ButtonGroup?

Assures only one button in the group is selected at a time

Which process is recommended for calculating the elapsed running time of an algorithm?

Calculate the difference obtained by calls to the method System.currentTimeMillis() just before the start of the algorithm and just after the end of the algorithm.

The event that is generated by a slider when its value changes is of type _____.

ChangeEvent

The ____ class contains a sort method that can sort array lists.

Collections

Which of the following statements about command line arguments is correct?

Command line arguments can be read using the main method's args parameter.

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

Which layout manager allows you to add components to it by invoking the container's add method with the component as the only argument to add. I FlowLayout II BorderLayout III GridLayout

I and III

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

Assuming that the string input contains the digits of an integer, without any additional characters, which expression obtains the corresponding numeric value?

Integer.parseInt(input)

What must be true about the return value from the implementation of the compare method for the Comparator interface when comparing two objects, a and b with a call to compare(a, b)?

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.

The method checkArray examines an array arr: public static boolean checkArray(int[] arr) { if (arr[0] >= arr[arr.length -1]) { return true; } return false; } What can you conclude about the running time of this section of code?

Its running time will be O(1).

Which of the following code statements creates a graphical button that has "Calculate" as its label ?

JButton button = new JButton("Calculate");

Which GUI element allows text entry from the program user?

JComboBox

All rodents are mammals and all canines are mammals. No canines are rodents and no rodents are canines. What hierarchy best captures this information?

Mammal is a superclass of Rodent and Mammal

An algorithm that tests whether the first array element is equal to any of the other array elements would be an ____ algorithm.

O(n)

What operation is least efficient in a LinkedList?

Random access of an element.

Which of the following algorithms would be efficiently executed using a LinkedList?

Remove first n/ 2 elements from a list of n elements.

You need to access values in the opposite order in which they were added (last in, first out), and not randomly. Which collection type should you use?

Stack

The _______ interface toolkit has a large set of user-interface components.

Swing

Assume inputFile is a Scanner object used to read data from a text file that contains a series of double values. Select an expression to complete the following code segment, which reads the values and prints them in standard output, one per line, in a field 15 characters wide, with two digits after the decimal point. while (inputFile.hasNextDouble()) { double value = inputFile.nextDouble(); ___________________________________ // statement to display double value }

System.out.printf("%15.2f\n",value);

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. public static void printBottom(Stack<String> theStack) { Stack<String> anotherStack = new Stack<>(); while (!theStack.empty()) { anotherStack.push(theStack.pop()); } ____________________________ while (!anotherStack.empty()) { theStack.push(anotherStack.pop()); } }

System.out.println(anotherStack.peek());

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 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.

Which of the following statements about the try/finally statement is NOT true?

The finally clause is executed after the exception is propagated to its handler.

When using the add method of the ListIterator to add an element to a linked list, which of the following statements is correct?

The new element is inserted before the iterator position, and a subsequent call to next would be unaffected.

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 call to the swap method call to read swap(i, minPos). What would be the result?

The sort would produce correct results.

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 catch exceptions that occur in the try block but will do nothing about the exceptions.

Consider the following code snippet that appears in a subclass: public void deposit(double amount) { transactionCount ++; deposit(amount); } Which of the following statements is true?

This method will call itself.

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?

This method will pass any IOException-type exception back to the caller.

When you implement equals in a subclass, you should first call equals in the superclass. Why?

To check whether the superclass instance variables match.

You need to access values using a key, and the keys must be sorted. Which collection type should you use?

TreeMap

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

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

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))

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

Given an ordered array with 31 elements, how many elements must be visited in the worst case of binary search?

5

Which of the following statements about a Java interface is NOT true?

A Java interface must contain more than one method.

When the reserved word super is followed by a parenthesis, what does it indicate?

A call to a superclass constructor.

Which of the following statements is correct about inheritance and interfaces?

A class can extend at most one class and can implement multiple interfaces.

Which of the following statements about superclasses and subclasses is true?

A subclass extends a superclass.

The term for a class from which you cannot create objects is

Abstract Class

When the user selects a menu item, the menu item sends a(n) ___________________.

ActionEvent

Which of the following is an example of a functional interface, having a single abstract method?

ActionListener

Which of the following statements about interfaces is NOT true?

An interface can describe the state that should be maintained.

Which of the following is true about interface types and abstract classes?

An interface type cannot have instance variables whereas an abstract class can.

A ________ is a user-interface component with two states: checked and unchecked.

check box

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 extends MouseAdapter

An ____ belongs to a class whose methods describe the actions to be taken when a user clicks a user-interface graphical object.

event listener

Consider the Counter class below. public class Counter { public int count = 0; public int getCount() { return count; } public void increment() { count++; } } Using the class above and the variables declared below, what is the value of num1.equals(num2)? Counter num1 = new Counter(); Counter num2 = new Counter();

false

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?

ghiabcdef

Insert the missing code in the following code fragment. This fragment is intended to read characters from a text file. Scanner in = new Scanner(. . .); in.useDelimiter(""); while (in.hasNext()) { char ch = ____________; System.out.println(ch); }

in.next().charAt(0)

The following code is an example of a ___ search. public static int search(int[] a, int v) { for (int i = 0; i < a.length; i++) { if (a[i] == v) { return i; } } return -1; }

linear

Assume you have created a linked list named myList that currently holds some number of String objects. Which of the following statements correctly adds a new element to the beginning of myList?

myList.addFirst("Harry");

Assume you have created a linked list named myList that currently holds some number of String objects. Which of the following statements correctly removes an element from the end of myList?

myList.removeLast();

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 = new File(inputFileName); Scanner in = _________; PrintWriter outFile = new PrintWriter("dataOut.txt"); . . . }

new Scanner(inputFile)

Which of the following adds a border to the following panel? JPanel panel = new JPanel();

panel.setBorder(new EtchedBorder());

Suppose the class Message is partially defined as shown below: public class Message { private String value; public Message(String initial) { value = initial; } public String getMessage() { return value; } } A subclass of Message, ExcitedMessage, is defined that will behave like Message, except that it will add two exclamation points to the end of the message. Sample code that uses ExcitedMessage is shown below. : ExcitedMessage greeting = new ExcitedMessage("Hello"); System.out.print(greeting.getMessage());// will print "Hello!!" Which ExcitedMessage constructor will give this behavior?

public ExcitedMessage(String line) { super(line + "!!"); }

Using the following definitions of the Measurable and Named interfaces. public interface Measurable { double getMeasure(); } public interface Named { double getName(); } Assume BankAccount provides the code for the getMeasure() and getName() methods. Which of the following could correctly represent the class header for BankAccount?

public class BankAccount implements Measurable, Named

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?

public class Motorcycle extends Vehicle

Print jobs submitted to a printer would probably be stored in which type of data structure?

queue

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?

queue

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

random access

Which of the following algorithms would be efficiently executed on an ArrayList?

read n / 2 elements in random order from a list of n elements

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?

return (score - otherGame.score)

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. public static int sumTwoLowestElements(int[] numbers) { PriorityQueue<Integer> values = new PriorityQueue<>(); for (int num: numbers) { values.add(num); } ______________________ }

return values.remove() + values.remove();

Another name for linear search is ____ search.

sequential

A collection without an intrinsic order is called a ____.

set

A complex GUI can be created with a set of nested panels. What should determine the components that go into a single panel?

the adjacency of the components

To test whether an object belongs to a particular type, use

the instanceof operator.

Insert the missing code in the following code fragment. This code is intended to open a file and handle the situation where the file cannot be found. public void String readFile() _________________ { File inputFile = new File(. . .); try (Scanner in = new Scanner(inputFile)) { while (in.hasNext()) { . . . } } }

throws IOException

Which String class method will remove spaces from the beginning and the end of a string?

trim()

The method below is designed to return the smaller of two Comparable objects received as arguments. Assume that the objects are instances of the same class. Select the correct expression to complete the method. public static Comparable smaller(Comparable value1, Comparable value2) { if (_________________________ ) return value1; else return value2); }

value1.compareTo(value2) < 0

Which function has a faster growth rate: θ(n1/2) or θ(log(n))?

θ(n1/2)

Consider the following code snippet: PriorityQueue<String> stringQueue = new PriorityQueue<>(); 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,

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[i].equals(item)


Ensembles d'études connexes

Drugs and Society Chapter 8 Test Review

View Set

Sociology 3rd Test Sample Questions

View Set

The Recording Process - Lecture 2 (Chapter 2)

View Set

Chapter 40: Disorders of the Female Genitourinary System-Patho Level 3

View Set

Chapter 5- Organizational Behavior

View Set

English Short Story Test 2 Review

View Set

Chapter 25 Law- Agency Liability Concepts

View Set