CSC202 Final

Ace your homework & exams now with Quizwiz!

A throw executed in a method automatically causes a jump to the last return statement in the method

F

After an exception is thrown and a catch block executes, execution resumes with the statement immediately after the statement that generated the exception.

F

For a generic class with a generic type parameter T, an appropriate instantiation of an object of that class would be Vehicle<T> v1 = new Vehicle<T>();

F

Given the following code that creates and initializes a HashSet HashSet<Character> guessedLetters = new HashSet<Character> (); guessedLetters.add('e');guessedLetters.add('t');guessedLetters.add('a'); What value will guessedLetters.remove('s') return?

F

In the base case, a recursive method calls itself with a smaller version of the original problem.

F

Running a program with an endless recursion error looks like running a program with an endless loop.

F

A checked exception must either be handled via try-catch constructs, or the method must specify that the appropriate exception type may be thrown by appending a throws clause to the method's definition.

T

A compiler generates an error message if a try block is not immediately followed by a catch block.

T

A's protected member method can be called by a member method of B.

T

Any algorithm that uses recursion can be re-coded to use loops instead.

T

Assuming the IDs are well distributed, the following is a well designed hash function for the scenario. Hash function: key % 250 Key: 5-digit customer ID Hash table size: 250

T

Given the following code that creates and initializes a LinkedList and ListIterator: LinkedList<Integer> numbersList = new LinkedList<Integer>(); ListIterator<Integer> numberIterator = null; numbersList.add(3);numbersList.add(1);numbersList.add(4);numberIterator = numbersList.listIterator(); What does numberIterator.hasNext() return after three calls to numberIterator.next()?

T

Given the following code that creates and initializes a LinkedList and ListIterator: LinkedList<Integer> numbersList = new LinkedList<Integer>(); ListIterator<Integer> numberIterator = null; numbersList.add(3);numbersList.add(1);numbersList.add(4);numberIterator = numbersList.listIterator(); What does numberIterator.hasNext() return the first time?

T

If no exception occurs during the execution of code in a try block, then the subsequent catch block is not executed.

T

This class is a good choice to use when your application will be storing a large amount of data in a list, and a lot of insertions and/or deletions are likely to take place.

LinkedList

For a well-designed hash table, searching requires _____ on average.

O(1)

In which of the big O notation complexity classes does finding the largest value in a sorted array belong?

O(1) constant (i.e. the time to run the algorithm is constant, not dependent on input size)

In which of the big O notation complexity classes is the merge sort runtime?

O(n log n) log-linear. An increase in input size results in a slightly greater than proportional increase in running time

In which of the big O notation complexity classes does finding the largest value in an unsorted array belong?

O(n) linear. An increase in input size results in a proportionally large increase in running time.

In which of the big O notation complexity classes is the selection sort?

O(n2) quadratic. An increase in input size results in a much greater increase in running time.

Determine the simplified Big O notation for 2*N3 + O(N2)

O(n^3)

Determine the simplified Big O notation for 3*N * O(N2)

O(n^3)

A collection that is accessed in last-in-first-out fashion is called

STACK

A class can extend only one class.

True

Consider the following class header. Which of the following statements is true?public class SubClass extends SuperClass

all are true

HashMap<String, Integer> playerScores = new HashMap<String, Integer>();playerScores.put("Jake", 14);playerScores.put("Pat", 26);playerScores.put("Hachin", 60);playerScores.put("Michiko", 21);playerScores.put("Pat", 31); Which of the following operations modify the HashMap? A) playerScores.putIfAbsent("Michiko", 17); B) playerScores.remove("Pat"); C) playerScores.clear();

b and C

A class can implement only one interface.

false

Fields in an interface are

final and static

What is the name of the clause used to ensure that contained statements are executed after the try and catch blocks.

finally

Given the following declaration, write an enhanced for loop to show the numbers in the collection on the console. List<Double> myNums = new ArrayList<Double>();

for(Double num: myNums){ system.out.print(num); }

This operator can be used to determine whether a reference variable references an object of a particular class.

instance

Given waitList, the tail node's data value is _____.

mary

Which of the following best expresses the base case in the recursive code below? private static int mystery(int n){if (n == 0)return 1;elsereturn n * mystery(n - 1);}

n = 0

Abstract methods in a super class must be ___________ in a concrete base class.

overridden

If you do not provide an access specifier, which of the following is the default?

package

Given the following code that creates and initializes a HashMap: HashMap<String, Integer> playerScores = new HashMap<String, Integer>();playerScores.put("Jake", 14);playerScores.put("Pat", 26);playerScores.put("Hachin", 60);playerScores.put("Michiko", 21);playerScores.put("Pat", 31); Write a statement to add a mapping for a player with your name and a score of 1.

playerScores.put("Michael", 1);

This search algorithm is adequate for small arrays but not for large arrays

sequential search

The constructor for a sub-class of Exception should

specify a message

If a list of Strings named namesList is {"Amelia", "Calliope", "Sandy"}, what will the list look like after the following statement? namesList.add("Barbie", 1);

{"Amelia", "Barbie", "Calliope", "Sandy"}

The following code can produce a FileNotFound exception. Add exception handling that will produce a message on the console without invoking the default exception handler. (In other words, the program executes and terminates normally.) public static void main(String[] args){FileReader freader;String fileName = "data.dat";freader = new FileReader(fileName);}

try{ freader = new Filereader(fileName); } catch(FileNotFoundException e) { System.out.println(e.getMessage()); }

Write an enhanced for loop that calculates the sum of all values within the sensorReadings ArrayList. Each element of the ArrayList is a Double. Declare any variables used. If an enhanced loop cannot be used for this purpose, explain why.

double sumValue = 0; double currentValue = 0; for (Double sensorReading: sensorReadings){ currentValue = sensorReading sumValue = sumValue + currentValue;}

Given the following code that creates and initializes a HashSet:HashSet<Integer> employeeIDs = new HashSet<Integer>();employeeIDs.add(1001);employeeIDs.add(1002);employeeIDs.add(1003); Write a statement that adds an employee ID 1337.

employeeIDs.add(1337);

Given the following code that creates and initializes a HashSet: HashSet<Integer> employeeIDs = new HashSet<Integer> (); employeeIDs.add(1001);employeeIDs.add(1002);employeeIDs.add(1003); Write a statement that removes the employeeID 1002

employeeIDs.remove(1002);

In the mystery method below, how many base cases are there? public static int mystery(int n){if (n == 0)return 0;else if (n == 1)return 1;elsereturn mystery(n - 1) + mystery(n - 2);

2

The following adjacency list represents bus routes. Ex: A commuter can take the bus from Belmont to Sonoma. How many buses are needed to go from Belmont to Hillsborough

2

Which of the numbered lines below has an error? 27 try { 28 if (weight < 0) {29 try new Exception("Invalid weight."); 30 }31 // do some stuff31 } 32 33 catch (Exception excpt) {34 System.out.println(excpt.getMessage());35 System.out.println("Cannot compute health info"); 36 }

29

Consider the following (chaining) hash table, and a hash function of key % 10. How many list elements are compared for HashSearch(valsTable, 40)?

3

Consider the following (linear probing) hash table and a hash function of key % 10. HashRemove(idsTable, 65) probes _____ buckets.

3

Given hash function of key % 5, in a hash table with linear probing, determine the insert location. HashInsert(numsTable, item 46)

3

Given the linked list numsList below, how many nodes will be visited when the following statement is executed? (numsList.indexOf(54)

3

HashMap<String, Integer> playerScores = new HashMap<String, Integer>();playerScores.put("Jake", 14);playerScores.put("Pat", 26);playerScores.put("Hachin", 60);playerScores.put("Michiko", 21);playerScores.put("Pat", 31); What will playerScores.get("Pat") return?

31

Given a hash table with 100 buckets and modulo hash function, in which bucket will HashInsert(table, item 334) insert item 334?

34

A modulo hash function for a 50 entry hash table is: key % _____

50

Class Dwelling has data members door1, door2, door3. A class House is derived from Dwelling and has data members wVal, xVal, yVal, zVal. Considering only Dwelling and House, the definition and initialization House h = new House(); creates how many data members?

7

For a binary mid-square hash function, how many bits are needed for a 200 entry hash table?

8

A hash table has buckets 0 to 9 and uses a hash function of key % 10. If the table is initially empty and the following inserts are applied in the order shown, the insert of which item results in a collision? HashInsert(hashTable, item 55)HashInsert(hashTable, item 90)HashInsert(hashTable, item 95)

95

Assuming the statement below is valid, which of the following is true? Class1 c = new Class2(1000); If a method named fred() exists only in Class1, then c.fred() will result in a call to the method in Class1 If a method named fred() exists only in Class2, then c.fred() will result in a call to the method in Class2 If a method named fred() exists only in Class2, then c.fred() will result in an error.

A and C

The following table shows the measurements of sorting a 20 element array, using the four sorts we studied. Which is the insertion sort?

C

A company will store all employees in a hash table. Each employee item consists of a name, department, and employee ID number. Which is the most appropriate key? Department

Employee ID

All classes directly or indirectly inherit from this class.

Object

In the __________ algorithm, the smallest value in the array is located and moved to position 0. then the next smallest value is located and moved to position 1. This process continues until all of the elements have been placed in their proper order.

Selection sort

Consider the following method header: public static <T extends Comparable<T>> TtripleMin(T item1, T item2, T item3) what happens if a call is TripleMin(i, j, k) but those arguments are of type Character?

The compiler creates a method with Character types and calls that method.

Consider the following method header: public static <T extends Comparable<T>> TtripleMin(T item1, T item2, T item3) What happens if a call is TripleMin(i, j, z), where i and j are Integers, but z is a String?

The compiler will generate an error, because T must be the same for all three arguments.

HashMap<string,integer> playerScores = new HashMap<string, integer="">();playerScores.put("Jake", 14);playerScores.put("Pat", 26);playerScores.put("Hachin", 60);playerScores.put("Michiko", 21);playerScores.put("Pat", 31); Write a single statement to update Jake's score to the value 34.

Your Answer: playerScores.put("Jake", 34);

Given the following code that creates and initializes a Queue: Queue<Integer> ordersQueue = new LinkedList<>();ordersQueue.add(351);ordersQueue.add(352);ordersQueue.add(353); Complete the statement to add the value 354 to the tail of queue ordersQueue._________;

add(354)

Why are generic classes used?

an consolidate a lot of code, instead of writing a method for each type you need, you can have a generic method that does it all in one. also is a bit of a safety net in case you are passing incorrect types at the same time, similar to how an interface works as a safety net.

A class that can serve as the basis for another class is called a _____ class.

base

Abstract classes cannot

be instantiated

To handle and exception gracefully, you

catch

Given the following code that creates and initializes a HashSet HashSet<Character> guessedLetters = new HashSet<Character> ();guessedLetters.add('e');guessedLetters.add('t');guessedLetters.add('a'); Write a single statement that adds to guessedLetters the variable favoriteLetter only if favoriteLetter does not already exist in the set.

guessedLetters.add(favoriteLetter);

Which of the following can be instantiated? (Which of the following can be used to create an object without subclassing?) A) an interface B) a class with an abstract method C) an abstract class

none

Write a generic method (not a method from a generic class) named showArea. The method has one parameter: a reference to an object of the Rectangle class (or any sub-class of Rectangle.) The method does not return anything. The method will display (on the console) the area of the object, using its getArea() method.

public <T extends Rectangle> void showArea(T rectangle){ System.output.print(rectangle.getArea());}

Write the class header for a class named Fred. The class has one generic type parameter.

public class Fred<T>{ }

Write a method header for a public method named calculateMean that takes a String argument named filename, and that returns a double, and may generate a FileNotFoundException

public double calculateMean(String filename) throws FileNotFoundException

This is adapted from the CodingBat.com site: We have a neat, orderly line of bunnies and each bunny has either two or three big floppy ears. The even numbered bunnies have 2 ears. The odd numbered bunnies have 3 ears. We want to compute the total number of ears for a given number of bunnies. Solve recursively (without loops or multiplication). Write the bunnyEars method, which takes a single argument: the number of bunnies, and returns the number of ears in the line of bunnies.bunnyEars(0) → 0bunnyEars(1) → 3bunnyEars(2) → 5

public int bunnyEars(int bunnies){ if (bunnies < 1) return 0; if(bunnies % 2 == 1)return 3 + bunnyEars2(bunnies-1);return 2 + bunnyEars2(bunnies-1);}

Write a method header named fred which overloads the following method in the superclass

public int fred(int num)

Write an interface named Nameable that specifies two methods: getName and setName. Both should be public. The setName method has one String parameter; no return value. The getName method has no parameters; it returns a String.

public interface Nameable{ public String getName(); public void setName(String name); }

Which of the sorting algorithms in the text is best expressed with a recursive implementation?

quick sort

To add an element e somewhere in a linked list, just after a node referenced by ref, you should use the statement:

ref.next = new Node(e, ref.next);

public static void mysterySort(int[] array){int startScan; // Starting position of the scanint index; // To hold a subscript valueint minIndex; // Element with smallest value in the scanint minValue; // The smallest value found in the scanfor (startScan = 0; startScan < (array.length-1); startScan++){minIndex = startScan;minValue = array[startScan];for(index = startScan + 1; index < array.length; index++){if (array[index] < minValue){minValue = array[index];minIndex = index;}}array[minIndex] = array[startScan];array[startScan] = minValue;}}

selection sort

Given the following code that creates and initializes a LinkedList and ListIterator: LinkedList<Integer> numbersList = new LinkedList<Integer> (); ListIterator<Integer> numberIterator = null; numbersList.add(3);numbersList.add(1);numbersList.add(4);numberIterator = numbersList.listIterator();numberIterator.next();numberIterator.__________; Complete (fill in the blank) the code above to replace the next list element with newDigit.

set(newDigit)

The following is an explicit call to the superclass's default constructor

super

Traversing a list begins with

the list's head node

to conveniently remove a non-head node from a singly-linked list, you need a reference to

the node just before the one to be removed

Which of the following best expresses the base case in the recursive code below? private void doSomething(Graphics g, int n, int p, int r){if (n > 0){g.another(p, p, r, r);doSomething(g, n-1, p + 1, r - 1);}}

when n = 0


Related study sets

8/11 Geometry - Area/Perimeter Practice

View Set

Chapter 9 - Void or Inexistent Contracts

View Set

22 Skeletal System 2: Appendicular Skeleton

View Set

MACHINING OPERATIONS AND MACHINE TOOLS

View Set

Medical Terminology, Module 9 Exercise 41

View Set

Sociology: Marriage and Family Ch. 1-3

View Set