CS 2110 Final

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

The asymptotic complexity (Big O notation) of the method that adds an item to a Stack is:

O(1)

Fill in the blank: New nodes are added to a binary heap on the lowest level from left-to-right such that the _____ property is not violated.

Shape - Adding an element in any other location (i.e. not at the lowest level from left-to-right) will violate the shape property. There cannot be holes in the binary heap and leaves can only exist on bottom level (level i) or the level above that (level i-1)

Which of the following is not a primitive type in Java?

String (primitive: char, int, double)q

When your professors were writing their Exam class, as defined below, they forgot to write a toString() method. public class Exam {String title;String date;ArrayList<String> questions;//...} However, when they were printing out the exams in a main() method later, they ended up calling toString() on an object of type Exam. If Java allows this to happen anyway, without an error or Exception, why does it still work?

The Exam class inherits the toString() method from the Object class

You have written a Song class.You would like to sort songs in one particular way. You want to sort your Songs using Collections.sort() since you do not wish to write your own sorting method. In order to be able to call Collections.sort(yourSongList) in the Song class, what change (if any) do you have to make to the Song class?

The Song class implements the Comparable Interface

What will the following code snippet print out? class Raspberry extends Fruit implements Boxable {...}Raspberry berry = new Raspberry();...System.out.println(berry instanceof Object);System.out.println(berry instanceof Fruit);System.out.println(berry instanceof Raspberry);System.out.println(berry instanceof Boxable);

TrueTrueTrueTrue

In the software development lifecycle there is a specific phase in which all testing occurs.

False

According to the Java documentation, if a null value is passed to an equals method, the equals method should always return false.

True

An Interface can only have fields if they are both static and final.

True

An algorithm is a process or set of precise rules to be followed in calculations or other problem-solving operations. The algorithm must also terminate in finite time.

True

Asymptotic Analysis is an estimate of time as a function of the input size, n, as n gets large.

True

Big O notation has a concept of a dominant (highest order) term. The dominant term is the single behavior within the algorithm that has the most significant impact on performance. When devising Big O notation for an algorithm, you can safely ignore all of the steps besides that dominant term, because, as the the number of inputs approach infinity, less dominant terms have an effectively invisible impact on performance.

True

Every class that you create in Java inherits from the Object class.

True

In Java, all parameters are always "pass by value".

True

Software engineering is both a technological and managerial discipline.

True

True or False? For a binary minheap, there is a top-down ordering where all nodes are smaller than ALL of its descendants. Whereas, for a binary search tree, there is a left-right ordering where all nodes in the left subtree of that node has a value less than the node, and all nodes in the right subtree of that node has a value greater than the node.

True

True or False? Methods written in the "Node" class of a tree are typically written recursively

True

When you overload a constructor, you are:

creating more than one constructor for a single class with different input parameters

Implementing an interface (like Comparable, for example) is worthwhile because

it allows you to reuse algorithms (such as max() and sort(), for example) with any class you create

If class X extends class Y, then X _____ Y must make sense. Out of the following, what is the best option to fill-in the blank?

"is-a"

You have just written a class for your new program, for a type of object that will be stored in a Set. What method must you override for this to work correctly?

.equals() - to be able to check equality

Javadoc comments begin with which of the following characters?

/**

Given these class definitions: public abstract class Animal {public abstract String toString();public void help(Animal o) {System.out.println(this + " helps " + o);}} public class Cat extends Animal {public String toString() {return "Cat";}public void help(Animal o) {System.out.println(this + " ignores " + o);}} public class Kitten extends Cat {public String toString() {return "Kitten";}public void play() {System.out.println(this + " playing");}} 1. What is the output of the following code: Cat c = new Kitten();c.play(); 2. What is the output of the following code: Animal c = new Cat();Animal k = new Kitten();c.help(k);

1. Animal playing 2. Cat ignores Kitten

If you wrote an ActionListener, you would need to implement one method. Fill in the blanks below for the name of the method and the input argument type (NOTE: this answer is CASE and SPACE sensitive - Hint: your answer should have no spaces, and must have EXACTLY the right casing. No partial credit for incorrect casing.):Note that in the code below, square brackets are used for curly brackets due to a limitation of Collab. class ButtonListener implements ActionListener [ public void (1) ( (2) e) [ //TODO: implement method ] ]

1. actionPerformed 2. ActionEvent

public class Point { int x = 0; int y = 0; String color = null; public Point(int x, int y, String color) { this.x = x; this.y = y; this.color = color; } public Point(Point p) { this.x = p.x; this.y = p.y; } public static void main(String[] args) { Point a = new Point(1, 2, "red"); Point b = new Point(2, 1, "blue"); Point c = new Point(a); }} 1. After this code runs, what is the x and y value of Point c? 2. What is the value of the color field for Point c?

1. x=1; y=2. - The copy constructor of the class is used, which copies x and y values from the object passed as an argument, in this case, Point a 2. null

What is wrong with the code snippet below? double[] values = new double[10]; values[10] = 5;

10 is not a valid index for this array.

What will the following code output? (assume all necessary imports have been made) (Note, "print" without the "ln" means the carriage return, or insertion of a new line, is not included with the output, so the output continues to print on the same line, e.g. 1,2) public class ChangeExample { public static void main(String[] args) { int x = 5; int returned = changeValue(x); System.out.print(returned); System.out.print(","); System.out.println(x); } public static int changeValue(int value) { value = value + 1; return value; } }

6, 5 - x is a primitive type, therefore a copy of its value is passed to the method. The method can change the copy, but the original value of x doesn't get changed. Therefore the answer is 6,5. (6=changed value returned by method. 5=untouched, original value of the value in variable x.)

What does the following code output? (assume all necessary imports have been made) (Note, "print" without the "ln" means the carriage return, or insertion of a new line, is not included with the output, so the output continues to print on the same line, e.g. 1,2) public class ChangeExample { public static void main(String[] args) { int[] x = { 5, 5, 5 }; int[] returned = changeValue(x); printArray(returned); // see note below System.out.print(" "); // print two spaces printArray(x); // see note below } public static int[] changeValue(int[] value) { for (int p = 0; p < value.length; p++) { value[p] = 7; } return value; } // Note: assume the method "printArray()" is correctly written that will print // the contents of the array out with a comma separating the values // (no comma at the end.) E.g. 1,2,3 }

7,7,7 7,7,7 - x is initialized with the values {5,5,5}. In the changeValue() method, a copy of x's memory address is passed into it. The changeValue() method reassigns each entry, replacing them one by one with the number 7. Therefore the returned value from the method is "7,7,7". Since the array was altered in memory, printing x after the call to the method also prints "7,7,7" since the method was able to change the original int array x. (Example of pass-by-value using a reference type -- the original IS altered.)

Consider the following Zoo class (assume all necessary imports have been made): public class Zoo { TreeMap<String, Integer> myZoo = new TreeMap<String, Integer>(); public Zoo(TreeMap<String, Integer> myZoo) { this.myZoo = myZoo; } public String toString() { String ret = ""; for(String key : myZoo.keySet()) { ret = ret + myZoo.get(key) + " "; } return ret; } } What would the following code output? TreeMap<String, Integer> zooAnimals = new TreeMap<String, Integer>(); zooAnimals.put("Tiger", 5); zooAnimals.put("Zebra", 12); zooAnimals.put("Elephant", 8); Zoo virginiaZoo = new Zoo(zooAnimals); System.out.println(virginiaZoo);

8 5 12) - printing associated values out in sorted order (based on keys) because of TreeMap! (Would not happen if it was a HashMap.)

Let's assume there are 500 items in our list, that have been sorted. In the worst case, about how many checks would Binary Search make to find a target value?

9 - The log based 2 of 500 is about 8.96, which means Binary Search would take approximately 9 checks in the worst case to find the target value.

Line 1: import static org.junit.Assert.*;Line 2: public class TaxiTest {Line 3: Line 4: public void testPickUpSuccess() {Line 5: Taxi t = new Taxi(12.00, 5);Line 6: assertTrue(t.pickUp(5));Line 7: } What is missing on Line 3 from the code above? (Assume the class "Taxi" has been correctly written.)

@Test

Consider the following code snippet: Vehicle aVehicle = new Vehicle(4,"gasoline");String s = aVehicle.toString(); Assume that the Vehicle class does not have an implemented 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 (memory address will be printed). 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 Vehicle class.

A

Run-time polymorphism in Java enables the ___ method to be called at ___. Select the appropriate combination of words below that correctly completes this sentence. A. most appropriate, run-time B. most appropriate, compile-time C. most convenient, run-time D. closest, run-time E. superclass', run-time

A

Which of the code snippets below has the correct format for a java for loop? A. for (int counter = 0; counter <= 10; counter++) { //do something } B. for (int counter = 0, counter <= 10, counter++) { //do something } C. for (int counter = 0, counter++, counter <= 10) { //do something } D. for (int counter = 0; counter = 10; counter++) { //do something }

A

Which of the following can be used to add a key-value pair to a HashMap? A. the put() method B. the add() method C. the += operator D. the newPair() method E. the addKeyValue() method

A

Which of the following statements about Big O notation is FALSE? A. An O(n) algorithm's run time (in seconds) will ALWAYS be faster than an O(n2) algorithm's run time (in seconds) B. You cannot sort an ArrayList faster than O(n log n) C. Constant time is O(1) D. An algorithm that takes 3n + 5 steps has the same complexity class as an algorithm that takes 4n + log(n) steps.

A

Which of the following conditions are true, provided x is 5 and y is 6? Select all that apply. A. x + 1 <= y B. x + 1 == y C. x + 1 >= y D. x + 1 != y

A, B, C

Mark all that are true: A. Implementing an interface gives objects instantiated by that class another type. B. Interface files (the code of the interface) has to have implemented methods (methods with a body.) C. Classes implementing an interface must implement (override and write bodies for) all of the interface's methods. D. An interface object can be created from the interface's constructor. E. A class can only implement one interface. F. Classes implementing an interface must implement (override and write bodies for) at least one (but not all) of the interface's methods.

A, C

What are the properties of a checked exception? Select all that apply. A. The compiler makes sure the exception is handled before compiling the code. B. The exceptions are the programmer's fault and are not caused by external circumstances. C. You must either catch or throw (using the throws clause) the exception in a method. D. These exceptions are fatal and the program should end when they occur.

A, C

Which of the following are examples of non-functional requirements (not functional, and not constraints). Select all that apply: A. The program should execute the query in 5 seconds or less B. The program should require all users to be authenticated C. The program should produce estimates of a outcome that are within 5% accuracy D. The program must be built on the Java Swing GUI framework

A, C - A and C are examples of non-functional requirements. B- Functional requirement D- Design, therefore not a requirement statement at all

Which of the following statements are true of exceptions? A. To compile, checked exceptions MUST be caught and handled, or declared in a throws statement. B. To compile, unchecked exceptions MUST be caught and handled, or declared in a throws statement. C. Unchecked exceptions cannot be caught. D. RuntimeExceptions are checked.

A. - Checked exceptions MUST be caught or handled before the code can compile.

Which of these statement pertaining to arrays and ArrayLists is true?

Adding members to an array may cause the array to go out of bounds, but this is not possible with ArrayLists.

Algorithm A is O(n2). This means...

Algorithm A's efficiency grows like a quadratic algorithm or grows more slowly

In a Try/Catch/Finally pattern, when is the finally clause is executed?

Always

What would be the best option if you wanted to create a data structure that is ONLY used for adding a role to other classes and has no method(s) implemented (that is, all methods are method stubs)?

An interface

What is true about requirement statements? A. Ambiguous, vague, untestable, and doesn't come from the client. B. Unambiguous, clear, testable, and comes from the client. C. Ambiguous, vague, untestable, and comes from the client. D. Unambiguous, clear, testable, and doesn't come from the client.

B

Which of the following are considered benefits of Test Driven Development (TDD.) A. Gives you an assurance that your code is 100% accurate. B. Forces the developer to think deeply about the specifications of the system before coding. C. If the code passes all of the unit tests then no other testing is required. D. None of the above

B

Which of the following statements about binary trees is correct? A. Each node in a binary tree has at least two child nodes. B. Each node in a binary tree has at most two child nodes. C. The number of child nodes for each node in a binary tree is any power of two. D. If divided down the middle from top to bottom, a binary tree must be symmetrical.

B

Which of the following statements about comparing objects is correct? A. The equals() method is used to compare whether two references are to the same object. B. The equals() method is used to compare whether two objects have identical data. C. The == operator is used to compare whether two objects have identical data. D. The equals() method and the == operator perform the same actions.

B

Which of the following is a primitive type? (Select all that apply.) A. Double B. char C. boolean D. byte E. Integer F. Boolean G. String

B, C, D

What are the suggested ways of adding a listener to two buttons, and have the buttons respond in different ways while preserving encapsulation? (Select all that apply.) A. Our class implements the actionListener interface and we implement two actionPerformed() methods. B. Register the same listener with both buttons and include an if-then statement in the single actionPerformed() method to check which button called the method C. Create two external classes that implement the actionListener interface and use them as listeners for the two buttons. D. Create two inner classes that implement the actionListener interface and use them as listeners for the two buttons. E. Create two anonymous classes (one for each button) that act as the button listeners while implementing the actionPerformed() methods.

B, D, E

In this type of testing, tests run strictly on expected output. No other attempt is made to validate logic or flow.

Black Box

Consider this statement: "Both Beagles and Labradors are Dogs. All Dogs are Animals." Assuming Beagles, Labradors, Dogs, and Animals are classes, which of the following statements is correct?

Both Labrador and Beagle are subclasses of Dog

A subclass object may choose to access the superclass' implementation of its overridden method by using the keyword ___. Out of the following, what is the best option to fill-in the blank? A. get B. download C. super D. override

C

Consider the following code snippet: ArrayList<Integer> num1 = new ArrayList<Integer>(); int data; Scanner in = new Scanner(System.in); for (int i = 0; i < 5; i++) { data = in.nextInt(); num1.add(data); if (data == 0 && num1.size() > 3) { num1.remove(num1.size() - 1); } } System.out.println("size is : " +num1.size()); What is the output of the given code snippet if the user enters 1,2,0,0,1 as the input? A. size is : 1 B. size is : 2 C. size is : 4 D. size is : 0

C

Consider the following code snippet: public static int check(ArrayList<Integer> chknum1){ int chk = 0; for(int i = 0; i < chknum1.size(); i++){ if(chknum1.get(i) == 0){ chk++; } } return chk; } Which one of the following is true about the check method in the given code snippet? A. The check method counts all the elements with value 0 in an ArrayList passed as a parameter to the method. B. The check method removes all the elements with value 0 from an ArrayList passed as a parameter to the method. C. The check method counts all the elements with value 0 in an ArrayList passed as a parameter to a method, and the method also returns the count. D. The check method adds 0 to the elements of an ArrayList as a parameter to a method, and the method also returns the ArrayList.

C

Consider the following code: Collection<String> players = new ArrayList<String>();// code to add elements to the collection hereif (players.contains(name)) {System.out.print(name + " is one of the players in the collection.");} Which answer best describes what will happen in this situation. A. This will not run as is and in order, for it to run we need to make the if statement if (players.indexOf(name) >= 0) B. The method contains is not included in the Collection interface, therefore, this will not run. C. The code will run just fine as contains is included in the Collection interface and because of runtime polymorphism, the contains method in the ArrayList class will be executed. D. The method contains is not included in the Collection interface but this will run because contains is a method in the ArrayList class.

C

Which of the following lines of code are a correct application of the substitution principle used in polymorphism? A. Dog dog = new Dog(); B. ArrayList<Animal> dogs = new ArrayList<Dog>(); C. Animal dog = new Dog(); D. Dog dog = new Animal(); E. ArrayList<Object> objs = new ArrayList<Animal>();

C

Which one of these is invalid Java syntax (i.e. not correct)? A. String hello = "You are doing awesome, " + "on this exam!"; B. char ch1 = 'a';char ch2 = 'a';int c = a+b; C. boolean a = true;boolean b = false;boolean c = a + b; D. double a = 43.5;int c = (int) a * 4;System.out.println(c);

C - You cannot add two boolean values together. Therefore the line "boolean c = a + b;" is invalid (not correct!). For the character (char) example, two chars can be added together because they are represented as ints (ASCII) in memory.

Which statement(s) about the size of a Java array, ArrayList, and String are true? 1. The syntax for determining the size of an array, an ArrayList, and a String in Java is consistent among the three 2. The String uses s.size(), while the ArrayList uses a.length() 3. The array uses a.length, which is not a method call

C. 3

Motivations for inheritance include: A. Code reuse B. Software that better matches the real world C. Flexible design D. All of the above

D

The substitutability principle: If Student is a subtype of UVaPerson, then objects of type ___ may be ___ with any object of type ___. Select the appropriate combination of words below that correctly completes this sentence. A. Student, replaced, UVaPerson B. Student, implemented, UVaPerson C. UVaPerson, paired, Student D. UVaPerson, replaced, Student

D

What becomes important when the size of the project becomes large ("programming in the large")? A. Risk B. Consequences C. Economics D. All of the above

D

Both .equals() and .compareTo() are methods inherited from the super class Object

False

Which one of the following statements is true about strings? A. Strings can not be passed as arguments to a method. B. Strings require the new operator. C. Strings are a primitive type. D. Strings are immutable.

D.Strings are immutable.

What does the following code output? (assume all necessary imports have been made) (Note, "print" without the "ln" means the carriage return, or insertion of a new line, is not included with the output, so the output continues to print on the same line, e.g. lion, tiger) public class NameEditor { public static void main(String[] args) { String name = "Fatimah"; System.out.print( alias(name) ); System.out.print(", "); // print a comma and two spaces System.out.println(name); } public static String alias(String name) { name = "DJ " + name; return name; } }

DJ Fatimah, Fatimah - Remember, Strings are immutable! The original string name would not change after the method is called (therefore, printing 'name' in the last line of the main method would print Fatimah, not DJ Fatimah.

Queues are a ______ structure that uses the ______ method to remove items.

FIFO (first in first out), remove()

A slower growing algorithm is a less efficient algorithm.

False

An abstract class can only have abstract methods.

False

An abstract class must have abstract methods.

False

Let's assume there is a Bird class, a Canary class, and a Parrot class. Both Canary and Parrot extend the Bird class. Let's also assume that a method called "youngest" exists and takes in an ArrayList of type Bird: public static void youngest(ArrayList<Bird> birdList) { . . . // some implementation} Would the following code compile? ArrayList<Canary> canaryList = new ArrayList<Canary>();canaryList.add(new Canary("Tweety", 3));canaryList.add(new Canary("Twitter", 6));canaryList.add(new Canary("Tiny", 4));youngest(canaryList); // call to youngest() method Answer false if you think the code will not compile; answer true if you think the code will compile.

False

True or False? A Queue is a good data structure for random access to elements.

False

True or False? For faster searching, a Stack should be sorted

False

True or False? Strings are a primitive type.

False

True or false, the pop() method for stacks does the same thing as the peek() method for queues.

False

When a Java program encounters an error, the program must exit.

False

True or False? A map data structure must use the same data type for both the key and associated value.

False - A map can have a data type for the key and another data type for the value. It is possible that the key and value share the same data type but it is not a must that this happens.

If you call the interrupt() method on a running thread, the thread will terminate immediately.

False - Calling interrupt() sets a flag property for that thread, but your code must check that flag and respond in some way. If you do not write this code, calling interrupt() will do nothing to that thread.

A Java program can be written entirely out of interfaces.

False - Interfaces can never be created as objects (interfaces are 100% abstract.)

True or False? Every class must include a main method.

False - Not all classes require a main method. A main method is useful if you want to do something. However you can create classes that do not have a main method and that would be perfectly fine - e.g. if the class consists of a number of static utility methods that other classes could call to use.

To work properly, the binary search algorithm can be run on any input array.

False - The array must be sorted to run binary search. While the binary search algorithm could run on any input array, it would only work properly if given a sorted array.

You are selecting a sorting algorithm for your application. Your choice is between two methods that each have quadratic order performance, that is they are both in the same complexity class, O(n2). True or False? It really doesn't matter which algorithm you select, the performance will be the same in practical use.

False - algorithms of a similar order can perform very differently.

To make a Map that maps an animal breed to the number of animals of that breed at the zoo (such as "zebra" -->5) what Map declaration and instantiation should you use?

HashMap<String,Integer> zooAnimals = new HashMap<String,Integer>();

In a Binary Search Tree (BST), where can you find the "next largest successor node" of a particular node?

In that node's right subtree, all the way to the left. - Values larger than the current node's value will always be in its right subtree. The "next largest successor node" would mean the smallest value out of all the larger values, so you'll find that value all the way to the left.

In big-Oh notation, suppose an algorithm is of order n3. How does doubling the size of the input affect the run time?

Increases the run time by a factor of approximately 8. (Given input size of n, the runtime of the algorithm will be approximately n^3. If we double the input size to 2n the runtime would be approximately (2n)^3 or 8n^3 which would increase the runtime by a factor of about 8.)

You have learned in class about three data structures: Lists, Sets, and Maps. One reason a developer should NOT opt for one particular data structure is:

Interoperability. Some of these data structures will work with primitive types, and some of them will not.

When making a GUI program, the class that creates your GUI window needs to extend which Java class?

JFrame

A function that belongs to a class is called a(n) ....

Method

The Comparable interface allows you to define __________ for the class.

Natural Order

What does Java expect a method to return if it is declared with the void keyword?

Nothing

Review the following method carefully. What is the complexity class of the method below? public static int method(int[] array){ for (int i : array){ for (int j : array){ return i+j; } } }

O(1) - constant - This algorithm returns the first time through both loops, which means both loops are only executed once. This means that the number of steps is not dependent on the size of the input and is therefore constant time!

If we assume we have a balanced Binary Search Tree, what is the Big-O runtime of the find and insert methods?

O(log n)

What is the asymptotic complexity of the following function? public static int a (int[] array) {int sum = 0;for (int i = 0; i < array.length; i++) {for (int k = 0; k < 1000; k++) {sum += array[(i+k)%array.length];}}return sum;}

O(n) Linear - the second for-loop doesn't "count" as it goes up to a fixed size, and therefore doesn't have any relationship with the actual size of the problem. Thus the overall complexity of this algorithm is O(n).

What is the asymptotic complexity for the following java code as it relates to the size of the array arr? for(int i = 0; i < arr.length; i++) {for (int j = 0; j < 5; j++) {arr[i]++;}}

O(n) linear - Feedback: Inner for-loop always iterates 5 times - no relationship to the input side. Therefore, this for-loop doesn't "count." The outer for-loop does count. So, the complexity class for this code is O(n) - Linear.

If you are designing a program for an automatic Car Wash, which data structure makes the most sense?

Queue

What will be the output of the code below if exceptionMethod() throws a MalformedURLException. try { System.out.print("R"); exceptionMethod(); //Exception is thrown by this call System.out.print("G"); } catch (Exception e){ System.out.print("K"); } finally { System.out.print("F"); }

RKF

Consider the following code snippet, which is meant to override the equals() method of the Object class: public class Coin { . . . public boolean equals(Coin otherCoin) { . . . } . . .} What is wrong with this code?

The argument is not the correct type; this method will not override the equals method in the Object superclass

What is the result of the following definition of an array list? ArrayList<Point> points; (Assume a Point class has been properly created.)

The statement defines an ArrayList reference but does not create an ArrayList.

What is the default behavior of the compareTo method in the Object class?

There is no compareTo method in the Object class

Consider the exceptions: ClassNotFoundException, ClassCastException, NumberFormatException, and Error. What class do all these exceptions inherit from?

Throwable

True or False? You can store an int (integer) value into a variable of type double without having to cast the int (integer) value first. (See example below.) int i = 5; // the integer value (5)double d = i; // storing i into a variable of type double

True

True or False? One of the most efficient implementations of a priority queue is achieved by using a binary heap

True - Binary heaps provide efficient implementations ( O(log n) ) for both the add and remove methods. If an array or ArrayList is used instead, one of the two methods is efficient and the other is inefficient - you cannot achieve efficiency in both methods.

True or False? Locks are only needed when a program uses more than one thread

True - If nothing is happening concurrently, there is no risk of a race condition occurring. Therefore, locks would not be needed.

A problem needs to be solved and there are two candidate algorithms. One is an exponential algorithm (O(2n)) and the other is a cubic algorithm (O(n3)). True of False? If 'n' (the problem size) is very small, either algorithm could result in better performance.

True - With the problem size, 'n', being so small, sometimes an inefficient algorithm could perform better than a more efficient one. It is not until 'n' gets large that the true nature of these algorithms start to show.

There are two versions of the Collections.sort() method. When using the Comparator interface, and overriding the appropriate method, the version of Collections.sort() method that will be used is the one that takes two parameters (instead of one).

True. - When using the Comparator interface, you will be writing a separate class that implements Comparator<YourObject> and overriding the compare() method. In the main class (YourObject class), the version of Collections.sort() that is used is the one that takes two parameters: Collections.sort(yourList, function object);

What is the output of treeHeights.toString() for the code below? TreeSet<Double> treeHeights = new TreeSet<Double>();treeHeights.add(2.3);treeHeights.add(10.0);treeHeights.add(2.3);treeHeights.add(10.0);treeHeights.remove(2.3);treeHeights.add(3.7);

[3.7,10.0]

If both of the child references of a binary tree node are null, it follows that the node must be ____.

a leaf node

Empirical testing refers to testing...

a set of observations

The code below is an example of what? javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } });

anonymous class

You have created a new Book class and wish to store your books in a binary search tree (BST) to be able to search for books efficiently. The only way to add items of type Book into a BST is by:

ensuring the Book class implements the Comparable interface (and a compareTo() method is written in the class) - The data variable should be a Comparable type (not Object) in order for the data comparisons to work. (The methods find, add, and delete all rely on the fact that items placed in a BST can be compared to one another) You can therefore store any kind of data into a BST as long as it is Comparable!

If you wish to use the contains() method with objects of your class (e.g. Point), you must ensure a properly-written __________ method exists in your class (e.g. in the Point class).

equals() - In order to use the contains() method, you must have a properly written equals() method in your class. The contains() method replies on the equals() method to be written, because it will call the equals() method multiple times in order to perform the behavior of checking if an element (of that type) is contained in a structure.

If you have a Java file, ExamSubmission.java, and you want to add a natural order for sorting ExamSubmission objects, which class should ExamSubmission implement?

implements Comparable<ExamSubmission>

You have created the class Book. The variable "numberOfPages" is probably a(n)

instance variable

In Java, what command is used to check if an object is of a given type?

instanceOf

In the class header "public Runner implements Racer{...}" Racer is a(n): (Choose the most specific and appropriate answer to describe Racer.)

interface

Which is typically the most expensive phase in the software development life cycle

maintenance

Based on the name, "setHeight" this method is probably a(n)

mutator method

In a UML class diagram the symbol + means what?

public

The Runnable interface has a(n) _______() method stub, which needs to be implemented when a class implements Runnable. This method contains the code that a thread should execute.

run() - The Runnable interface has a run() method stub which needs to be implemented when a class implements this interface.

What is the difference between using super and super() in a Java method?

super is used to call a super class's method (such as super.methodA()), while super() to call the super class's constructor

Let's assume class Student is a super class and class GraduateStudent extends Student (GraduateStudent is a subclass to Student.) Assume the Student class looks something like this: class Student { // super class String name; int gpa; public Student(String name, int gpa) { this.name = name; this.gpa = gpa; } . . . // assume rest of class written} In the constructor of the GraduateStudent class, a call to "super" has to be made. What is the appropriate syntax and parameters for the call to super in the GraduateStudent constructor, given the following fragment of the GraduateStudent class? class GraduateStudent extends Student { // sub class String advisorName; public GraduateStudent(String name, int gpa, String advisorName) { {How to call "super" here } . . . // assume rest of code written here } . . . // assume rest of class written}

super(name, gpa);

Suppose that s and t are Strings and that s.compareTo(t) returns 5. Which of the following statements is correct.

t is "less" than s. In other words, t should be listed before s.

HashMap <String, Donkey> donkeyMap = new HashMap <String,Donkey>(); In the line of code above, the types identified in brackets, <String, Donkey>, indicate:

the HashMap uses a String object as a key to store Donkey objects

The "shape" and "order" properties do work together to create an effective and efficient binary minheap. However, the fact that the smallest element in a binary minheap is always found at the root is mostly due to:

the order property - Even when you add a new element or remove from the data structure, the current smallest element finds its way to the root of the tree mostly due to the order property when swapping elements upwards or downwards.

A race condition, essentially, is when

the order the threads complete determines the outcome of the program.

Analyzing an algorithm with Big O notation is useful for predicting

the performance of the algorithm as different amounts of inputs are processed

In the "Binary Tree" class (that defines the tree) there must be a specific reference pointer to:

the root of the tree

What course of action should be followed when a thread has been interrupted (due to an exception)?

the thread should execute the code in the appropriate catch block

You have an instance variable "double width" for class "Apple" and the method "public void setWidth(double width)". The main statement inside the setWidth method should be:

this.width = width;

When using a Map data structure, all of the key objects must be unique.

true

If the Banana class implements the Fruit interface, what is the output of the statements below: Banana b = new Banana(); System.out.print(b instanceof Object); System.out.print(b instanceof Banana); System.out.print(b instanceof Fruit); (NOTE: I used .print() so that all outputs are printed on the same line.)

truetruetrue

A _______ defines the set of values that a variable can hold, as well as the operations that can be applied on these values.

type

A benefit of using generics (e.g. ArrayList<T> or Map<K, V>) is:

type safety

A solution to fix the issue of a race condition on a shared resource is to:

use a Lock object - Code that manipulates the shared resource is surrounded by calls to .lock() and .unlock().

Observe the following snippet of code in the main method of a class. Let's assume code has been written to simulate a phone book by using a TreeMap (named phoneBook), where names (String) are paired with phone numbers (int). What is the output when the following lines of code are executed? (Assume the TreeMap has been correctly created and nothing else has been added to the TreeMap. Also assume all necessary imports have been provided.) phoneBook.put("Lorna", 321);phoneBook.put("Anna", 456);phoneBook.put("Grace", 789);phoneBook.put("Clayton", 333);phoneBook.put("Clayton", 115); System.out.println(phoneBook);

{Anna=456, Clayton=115, Grace=789, Lorna=321} The key-value pairs are printed out in sorted order (ordered by the keys). The second call to the put() method when provided with the same key ("Clayton") simply modifies the value of the existing key ("Clayton") changing it from 333 to 115. Clayton and its associated value 333 is no longer preserved in the TreeSet (it is over-written).


Set pelajaran terkait

injury, management and recovery test 4

View Set

*HURST REVIEW Qbank/Customize Quiz - Pharmacology

View Set

Human Development Chapter 6 Study Guide

View Set

US History 8: The Development of Colonial America: Mastery Test

View Set