COMP 2150 Final Exam
What is the difference between Comparator and Comparable in Java programming?
1. Comparable has a single sorting sequence. 2. Comparator has multiple sorting sequences.
Fruit f1 = new Fruit(); Fruit[] fa; Banana b = new Banana(7); Citrus c = new Lemon("Meyer"); Grapefruit g = new Grapefruit(15); Lemon lm = new Lemon("Lisbon"); Circle all assignment statements that would be acceptable to the Java compiler. (# 3 has two choices) 1. a) g = b; b) b = g; c) g = f1 d) f1 = g 2. a) lm = c; b) c = lm; c) g = lm d) b = lm 3. a) b = c; b) f1 = c; c) c = g d) g = c 4. a) b = f1; b) fa = b; c) f1 = b d) b = fa
1. d) f1 = g; 2. b) c = lm; 3. b) f1 = c; c = g; 4. c) f1 = b
How many String objects are instantiated by the following code segment? String s1, output; s1 = "hello"; output = "\nThe string reversed is: "; for (int i = s1.length() - 1; i >= 0; i--) output += s1.charAt(i) + " ";
7
What is the difference between Collections and Collection in Java Collection Framework?
A collection is an interface. Collections is are static methods that perform operations for the collection interface
What happens when a new element is added to an arrayList that's at maximum capacity?
A new larger array is created, and the old elements are copied over.
An interface name can be used to declare a reference variable? A) True B) False
A) True
Suppose X is an abstract class, Y is a concrete subclass of X, and both X and Y has a default constructor. Which of the following is correct? (more than one answer) A. X a = new X(); B. X a = new Y(); C. Y b = new X(); D) Y b = new Y();
A. X a = new Y(); D. Y b = new Y();
(1) What is garbage collection in the context of java? a. The operating system periodically deletes all the java files available but not used on the system. b. Any package imported in a program and not used is automatically deleted. c. When all references to an object are gone, the memory used by the object is automatically reclaimed. d. The JVM checks the output of any Java program and deletes anything that doesn't make sense. e. The JVM set a reference variable to null and when it is not in-use for a long period.
Anc. C
(1) When a parent variable refers to a child object and a method is called on that object, the proper implementation is determined at execution time. What is the process of determining the correct method to call? A. early binding. B. non-binding. C on-time binding. D. late binding. E. compile-time binding. F. smart- binding
Ans (D)
String s1, output; s1 = "buzzer"; output = "\nThe string reversed is: " ; for (int i = s1.length() - 1; i >= 0; i--) output += s1.charAt(i) + " " ; A. 1 B. 8 C. 5 D. 7 E.4
Ans = B
(1) Which of the following is true? (circle the right answers) a) In java, an instance field declared public generates a compilation error. b) Object Oriented programming (OOP) is faster and easier to learn is general. c) Instance variable names may only contain letters and digits. d) A java class always has a constructor (implicit or explicit) e) In OOP, Inheritance is fundamental to abstraction, encapsulation, and polymorphism.
Ans d
(1) What will be the output of the below program? package com.Quiz2; class X1{ void calculate(int a, int b) { System.out.println("Class X " + (a + b)); } } class Y1 extends X1{ @Override void calculate(int a, int b) { System.out.println("Class Y " + (a + b)); } } class Z1 extends Y1{ @Override void calculate(int a, int b) { System.out.println("Class Z " + (a + b)); } } public class Q2MC5 { public static void main(String[] args) { X1 x = new Y1(); x.calculate(10, 20); Y1 y = (Y1) x; y.calculate(50, 100); Z1 z = (Z1) y; z.calculate(100, 200); } }
Ans: (4 points for correct I and II... 1 point for iii) I. Class Y 30 II. Class Y 150 III. Z z = (Z) y) will throw java.lang.ClassCastException at run time. Because, Y cannot be cast to Z.
(1) What will be the output of the following program? package com.Quiz2; class X { void method(int a) { System.out.println("ONE"); } void method(double d) { System.out.println("TWO"); } } class Y extends X { @Override void method(double d) { System.out.println("THREE"); } } public class Q2MC3 { public static void main(String[] args) { new Y().method(100); } } A. THREE B. TWO C: ONE D:100 E: Compile error
Ans: C
(1) (3 points) Which statement best describes the relationship between superclass and subclass types? A. A subclass reference cannot be assigned to a superclass variable and a superclass reference cannot be assigned to a subclass variable. B. A subclass reference can be assigned to a superclass variable and a superclass reference can be assigned to a subclass variable. C. A subclass reference can be assigned to a superclass variable, but a superclass reference cannot be assigned to a subclass variable. D. A superclass reference can be assigned to a subclass variable, but a subclass reference cannot be assigned to a superclass variable. E. A superclass reference can be assigned to a subclass variable, and a subclass reference can be assigned to a superclass variable.
Ans: D. A superclass reference can be assigned to a subclass variable, but a subclass reference cannot be assigned to a superclass variable.
(1) What will be the output of the below program? package com.Quiz2; public class Q2MC4 { double m1(double d) { return d *= d; } int m1(int i) { return m1(i *= i); } float m1(float f) { return m1(f *= f); } public static void main(String[] args) { Q2MC4 main = new Q2MC4(); System.out.println(main.m1(10)); } } A: 10, B: 100.0 C: 20.0 D: compiler error E: Runtime Error.
Ans: E
(1) ) Which statement is not true in java language? a. A public member of a class can be accessed in all the packages. b. A private member of a class cannot be accessed by the methods of the same class. c. A private member of a class cannot be accessed by the method of a different class. d. A protected member of a class cannot be accessed by the method of a class in different package.. e. None of the above.
Answer= b
What exception type does the following program throw? public class Test { public static void main(String[] args){ int[] list = new int[5]; System.out.println(list[5]); } }
ArrayIndexOutOfBoundsException
A List cannot contain duplicate elements is _____ A) True B) False
B) False
All classes in Java are directly or indirectly subclasses of the _______ class A) SuperClass B) Object C) This D) Class E) Abstract Class F) Concrete Class
B) Object
Which of these keywords cannot be used for a class which has been declared final? A. Protected B. abstract C. extends D. Both B & C E. Interface F.implement
B) abstract
__________ enable programmers to specify, with a single method declaration, a set of related methods, A) Overloaded Methods B) Overriding Methods C) Generic Methods D) Generic Class E) Generics List
C) Generic Methods
All of the following methods are implicitly final except: A. a private method. B. a method declared in a final class. C. static method D. a method in an abstract class E. Methods that cannot be overridden.
C) static method
Which of the following is correct to create a list from an array? A. new List<String>({"red", "green", "blue"}) B. new List<String>(new String[]{"red", "green", "blue"}) C. Arrays.asList<String>(new String[]{"red", "green", "blue"}) D. new ArrayList<String>(new String[]{"red", "green", "blue"}) E. new List (new String[]{"red", "green", "blue"})
C. Arrays.asList<String>(new String[]{"red", "green", "blue"})
What is the difference between capacity and size of an ArrayList?
Capacity: the maximum number of items an arraylist can currently hold without being extended Size: the current number of items stored in the ArrayList
Suppose you replace s with a Queue<String> object. The push calls are replaced with enqueue; the pop calls are replaced with dequeue. What element is at the front of the queue after the code executes?
Cody
When a class implements an interface (pre Java 8), it must : A) Overload all the methods listed in the interface B) Must have an explicit constructor C) Be an abstractor class with methods that have no conflicts with interface methods D) Provide all methods that are listed in the interface, with the exact signatures and returned types specified E) Extended from Object Class which is the top of ALL classes.
D) Provide all methods that are listed in the interface, with the exact signatures and returned types specified
In a subclass constructor, a call to the superclass constructor must: A. Appear just outside of the subclass constructor B. Appear as the very last statement C. Appear between the constructor's header and the open brace D. Appear as the very first statement E. Appear anywhere within the constructor, the compiler will handle it F. Not Appear
D) appear as the very first statement
Non-abstract classes are called___________. A.real class B. instance classes C. implementable classes D. concrete classes E. Derived classes F. Interface
D. Concrete classes
Generics provide _______ that allows programmers to catch invalid types early. A) Compile-time warning B) Compile-time exception handling C) Compile-time error checking D) Compile-time exception handling E) Compile-time type safety F) Run-Time error checking
E) Compile-time type safety
Which of the following statement is false? A. A list is a collection. B. Lists use zero-based indices C. A list can be an ArrayList type D. List is an interface type E. A list is sometimes called a sequence F. A list can contain dupilcate elements
E. A list is sometimes called a sequence
Java Class relationships in Inheritance vs. Composition is also known as the A) Concrete relationship vs Abstract relationship B) has-a relationship vs kind-of relationship D) is-a relationship vs Abstract relationship E) has-a relationship vs is-a relationship F) is-a relationship vs has-a relationship G) Abstract relation vs interface relation
F) is-a relationship vs. has-a relationship
What is the difference between an is-a and a has relation? How do you create a has-a relationship in Java code (for example: Student has an address)
Is a: class Circle extends Shape {......} a class inherits Shape's members because it is a Shape type. Has a: class Circle extends Shape { Triangle x1; Public Circle { this.x1 = new Triangle(); has a triangle object inside Circle class
What are the roles of the java keyword, super
It calls the subclass' superclass and executes the superclass. Access parent members (methods,constructors, public attributes, etc...)
// Assume s is an initially empty Stack<String> object s.push("Ellen"); s.pop(); s.push("Grant"); s.push("Cody"); s.push("Michael"); s.peek(); s.push("Xin"); s.pop(); s.peek(); What element is at the top of the stack after the code executes?
Michael
Letters is an ArrayList that has a bunch of letters contains "A" (eg {"A","A","B","A"} ). Does the following code correctly remove all elements with value "A" from the list? Explain the details during each iteration. for (int i = 0; i < letters.size(); i++) letters.remove("A");
No. iteration 1: i=0 size=4 first "A" removed size becomes 3 Iteration 2: i=1 size=3 second "A" removed size becomes 2 Iteration 3: i=2 for loop terminates as condition is false
Suppose you want to visit every element of a single linked list. You start by creating an iterator over the list, then repeatedly call the iterator's next method until it runs out of elements. What's the overall Big-O (tightest possible bound) of this loop?
O(n)
Suppose you want to visit every element of a single linked list. You write a loop that repeatedly calls get on each list Index - list.get(0), list.get(1), list.get(2), and so on. Assuming get is written the way that we did and used in our assignment exercise, what's the overall Big-O (tightest possible bound) of this loop?
O(n²)
Which best describes the basic stack operations?
Push, pop, and peek are all done from the top of the stack
Which best describes how to add a new element to the front of an arrayList?
Shift all existing elements up by one index, and insert the new element at index 0
What are the similarities and differences between Array and ArrayList as we discussed in class?
Similarities• Both can store a number of references• The data can be accessed via an index. Differences• ArrayList can automatically increase in capacity as necessary• ArrayList requests more space from the Java run-time system, if necessary. ArrayList is not ideal in its use of memory.
(1) Reference Variables can be polymorphic, what does that mean (1 point)? Use java codes to explain. (2 points)
Since a reference variable can hold a reference to objects of its derived class, An object of a subtype (subclass) can be used wherever its supertype (superclass) value is needed (superclass object is used). OR: It is when a single variable is used with several different types of related objects at different places in a program (one point below ...) Class Circle extends Shape { ....} Shape s1 = new circle ( ); // s1 can dynamically bind to method of different subclass of the Shape type.
What are the type parameters naming conventions used in Generics?
T, E, K, N, V
The Object Class
The mother of all objects. It is the super class of all classes made. The parent class for which all objects are from top of hierchy
Method Overriding
When a child inherits a method, but provides a different implementation (same name / signature)
Method Overloading
When there are multiple methods with the same method name but with different parameters.
Use the Big O notation to estimate the time complexity of the following methods. a) public static void mA(int n) { for (int i = 0; i < n; i++) { System.out.print(Math.random()); } } b) public static void mB(int n) { for (int i = 0; i < n; i++) { for (int j = 0; j < i; j++) System.out.print(Math.random()); } } c) public static void mC(int[] m) { for (int i = 0; i < m.length; i++) { for (int j = 0; j < i; j++) System.out.print(m[i] * m[j]); } } d) public static void mD(int[] m) { for (int i = 0; i < m.length; i++) { System.out.print(m[i]); } for (int i = m.length - 1; i >= 0; ) { System.out.print(m[i]); i--; } } E) Int Sum = 0; for (int i = 0; i < n; i++) { for (int j = 1; j <= i; j += 2) sum += 4; } for (int k = - 100 ; k <= -1; k++) sum--;
a) Ans: O(n) b) Ans: O(n^2) c) Ans: O(n) d)Answer: O(n^2) e)Ans: O(n2 log n).
Is ArrayList<?> same as ArrayList<? extends Object>? a) Yes b) No
a) Yes
23.) ____ is a data structure to store data in a sequential order. a. A list b. A set c. A BST d. A stack e. A queue f. A Map
a. A list
17.) Which of the following statements are true? a. All of the methods in HashSet are inherited from the Collection interface. b. All of the methods in TreeSet are inherited from the Collection interface. c. All of the methods in LinkedHashSet are inherited from the Collection interface. d. All of the methods in the Set are inherited from the Collection interface. e. All the concrete classes of Collection have at least two constructors. One is the no-arg constructor that constructs an empty collection. The other constructs instances from a collection.
a. All of the methods in HashSet are inherited from the Collection interface c. All of the methods in LinkedHashSet are inherited from the Collection interface. d. All the methods in the Set are inherited from the Colection interface.
34.) Chaining and probing are two methods used to resolve collisions in hash tables so that the amortized access time is O(1). For each of the following claims, indicate whether it is true of chaining, probing, both, or neither. (match each statement below to one of the 4 items.) a. Needs additional memory beyond the primary array for the hash table. b. Requires doubling the table periodically. c. May be either "linear" or "quadratic' d. Crashes if the load factor becomes greater than 1 e. Requires computing the hash function multiple times when doing an insertion.
a. Chaining b. Probing c. Probing d. Chaining e. Probing
What is the different between implicit constructor and explicit constructor?
a. Explicit constructor is done by a programmer b. Implicit constructor is done by the JVM compiler (a no-argument constructor)
16.) The Collection interface is the base interface for ________. a. Set b. List c. ArrayList d. LinkedList e. Map f. All of the above
a. Set b. List c. ArrayList d. LinkedList
15.) The elements in _______ are stored. a. TreeSet b. List c. TreeMap d. HashSet e. LinkedHashSet
a. TreeSet
32.) Answer the following questions with either true or false. Assume there are in elements in the data structure. No explanation necessary. a. One can implement a stack based on a linked list so that EACH INDIVIDUAL push/pop operation is time O(1) b. One can implement a stack (of unbounded size) based on an array so that each individual push/pop operations is time O(1) c. One can reverse the order of the elements in a linked list in time O(n). d. It is possible to append two linked lists in time O(1). e. Adding an element to a heap has worst-case time complexity O(log(n)). f. Returning the maximum element in a max-heap (but not deleting it from the heap can be done in time O(1).
a. True b. False c. True d. True e. True f. True
5.) Which of the following statements are true? a. java.util.LinkedList implements the java.util.Queue interface. b. java.util.ArrayList implements the java.util.Qeue interface. c. java.util.Hashset implements the java.util.Qeue interface. d. java.util.LinkedHashset implements the java.util.Qeue interface. e. java.util.PriorityQueue implements the java.util.Queue interface.
a. java.util.LinkedList implements the java.util.Queue interface. e. java.util.PriorityQueue implements the java.util.Queue interface.
Which of the following statements are true about abstract classes? (more than one answer) a.) An abstract method cannot be contained in a non-abstract class b.) If a subclass of an abstract superclass does not implement all the abstract methods, the subclass must be declared abstract. c.) An abstract class cannot be instantiated using the new operator. d.) It is possible to declare an abstract class that contains no abstract methods. e.) A subclass can be abstract even if its superclass is concrete.
a.) An abstract method cannot be contained in a non-abstract class b.) If a subclass of an abstract superclass does not implement all the abstract methods, the subclass must be declared abstract. c.) An abstract class cannot be instantiated using the new operator. d.) It is possible to declare an abstract class that contains no abstract methods. e.) A subclass can be abstract even if its superclass is concrete.
(1) Method signature consists of a) Method Name, Return Type and Number Of Argument b) Access Modifier, Method Name and Types Of Argument c) Method Name, Number Of Arguments, Types Of Arguments and Order Of Arguments d) Return Type, Access Modifier and Order Of Arguments Method Name, Number Of Arguments, Types Of Arguments
ans c) Method Name, Number Of Arguments, Types Of Arguments and Order Of Arguments
(1) To instantiate the Class Circle, you can use (circle all the right answers) a. Circle c1; b. Circle c1 = Circle( ); c. Circle c1 = Circle; d. Circle C1 = new Circle( ); e. Circle c1 = new Circle( ); f. New Circle( ); g. The constructor of Circle should be defined as public void Circle( ) { };
ans: d, e, f,
2.) Is ArrayList<Integer> a subclass of ArrayList<Object> ? a) Yes b) No
b) No
22.) Which of the following big O notation is O(nlogn) ? a. 300n + 400n*n b. 23nlogn + 9999 c. 45n + 45nlogn + 5000 d. n*n*n + nlogn + 99999 e. n + 99logn f. none of the above
b. 23nlogn + 9999 c. 45n + 45nlogn + 5000
Which of the following can be used to replace YYYYYYYY in the following code? public class WildCardDemo3 { public static void main(String[] args){ GenericStack<String> stack1 = new GenericStack<>(); GenerickStack<Object> stack2 = new GenericStack<>(); stack2.push("Java"); stack2.push(2); stack1.push("CSharp"); add(stack1, stack2); WildCardDemo2.print(stack2); } public static <T> void add(GenericStack<T> stack1, GenericStack<YYYYYYYY> stack2){ while(!stack1.isEmpty()) stack2.push(stack1.pop()); } } a. ? super Object b. ? super T c. ? extends T d. ? extends superT e. ? extends Object
b. ? super T
12..) Analyze the following code: public class Test{ public static void main(String[] args){ Map<String, String> map = new HashMap<>(); map.put("23", Michael Jordan"); map.put("30", Steve Curry"); map.put("23", Lebron James"); map.put("11", Clay Thompson"); } } a. After all the four entries are added to the map, "23" is a key that corresponds to the value "Michael Jordan". b. After all the four entries are added to the map, "23" is a key that corresponds to the value "LeBron James". c. After all the four entries are added to the map, "Clay Thompson" is a key that corresponds to the value "11". d. After all the four entries are added to the map, "Michael Jordan" is a key that corresponds to the value "23". e. A runtime error occurs because two entries with the same key "23" are added to the map.
b. After all the four entries are added to the map, "23" is a key that corresponds to the value "LeBron James".
27.) Suppose list1 is an MyArrayList and list2 is a MyLinkedList. Both contain 1 million double values. Analyze the following code: A: while(list1.size() > 0) list1.remove(0); B.: while(list2.size() > 0) list2.remove(0); a. Code fragment A runs faster than code fragment B. b. Code fragment B runs faster than code fragment A. c. Code fragment A runs as fast as code fragment B. d. Code fragment A runs faster only slightly. e. Impossible to compare.
b. Code fragment B runs faster than code fragment A.
13.) Suppose your program frequently test whether a student is in a soccer team and also need to know the student's information such as phone number, address, and age, what is the best data structure to store the students in a soccer team? a. ArrayList b. HashMap c. TreMap .d LinkedList e. HashSet
b. HashMap
If you want to store non-duplicated Objects in the order in which they are inserted, you should use: a. HashSet b. LinkedHashSet c. TreeSet d. ArrayList e. LinkedList
b. LinkedHashSet
26.) In the implementation of MyLinkedList, which of the following are true? a. MyLinkedList has a capacity property. b. MyLinkedList has the properties named first and last to point to the nodes in a linked list. c. If a linked list is empty, first is null and last is null. d. If a linked list contains one element, first points to the mode and last is null. e. last.next is always null. f. All of the above
b. MyLinkedList has the properties named first and last to point to the nodes in a linked list. c. If a linked list is empty, first is null and last is null. e. last.next is always null.
6.) What does the following codes display? import.java.util.* public class Test { public static void main(String[] args){ PriorityQueue<Integer> Queue = new PriorityQueue<Integer> { Arrays.asList(60, 10, 50, 30, 40 20)); while(!queue.isEmpty()) System.out.print(queue.poll() + " "); } } a. The program displays 60 10 50 30 40 20 b. The program displays 10 20 30 40 50 60 c. The program displays 60 50 40 30 20 10 d. There is no guarantee that the program displays 10 20 30 40 50 60
b. The program displays 10 20 30 40 50 60
All generic method declarations have a type parameter section delimited by __________. a. curly brackets ({ and }). b. angle brackets (< and >). c. square brackets ([ and ] ). d. parenthesis.
b. angle brackets (< and >).
25.) In the implementation of MyArrayList, which of the following are true? a. size never reduces. b. capacity never reduces. c. inside MyArrayList, a regular array is used to store elements. d. size is not declared in MyArrayList, but declared in MyAbstract List as protected. e. If the current capacity equals to size, capacity is doubled when a new element is added to MyArrayList f. All of the above
b. capacity never reduces c. inside MyArrayList, a regular array is used to store elements. d. size is not declared in MyArrayList, but declared in MyAbstractList as protected. e. If the current capacity equals to size, capacity is doubled when a new element is added to MyArrayList
Fields (aka attributes) in an interface are:
both final and static.
Which statement is false? a. A generic method may be overloaded. b. A class can provide two or more generic methods that specify the same method name but different method parameters. c. A generic method cannot be overloaded by non-generic methods. d. When the compiler encounters a method call, it searches for the method declaration that most precisely matches the method name and the argument types specified in the call.
c. A generic method cannot be overloaded by non-generic methods.
Which of the following statements is false? a. Wildcard type arguments enable you to specify method parameters, return values, variables, and so on, that act as supertypes of parameterized types. b. A wildcard-type argument is denoted by ?, which represents an "unknown type." c. Because a wildcard is a type-parameter name, you can use it as a type name throughout a method's body. d. If a wildcard is specified without an upper bound, then only the methods of type Object can be invoked on values of the wildcard type.
c. Because a wildcard is a type-parameter name, you can use it as a type name throughout a method's body.
Which of the following statements is true? a. Overloaded methods are often used to perform similar operations on different types of data. b. When the compiler encounters a method call, it attempts to locate a method declaration with a name and parameters that are compatible with the argument types in the method call. c. Both a) and b) are true. d. Neither a) nor b) is true.
c. Both a) and b) are true.
Which of the following statement is false? a. When declaring a generic method, the type parameter section is placed before the return type of the method. b. A type parameter is an identifier that specifies a generic type name. c. Each type parameter section contains only one type parameter d. Type parameters can represent only reference types.
c. Each type parameter section contains only one type parameter
28.) In the implementation of MyStack and MyQueue, which of the following are true? a. MyStack contains all the methods defined in MyArrayList. b. MyQueue contains all the methods defined in MyLinkedList. c. MyStack contains an array list for storing elements. d. MyQueue contains a linked list for storing elements. e. None of the above
c. MyStack contains an array list for storing elements.
29.) During hashing, a collision occurs ________ a. When two or more hash values are mapped in the same key. b. When two or more key values are the same. c. When two or more keys are mapped to the same hash value. d. When two elements have the same key value. e. When two elements are mapped to the same key.
c. When two or more keys are mapped to the same hash value.
8.) What is the output of the following code? import.java.util.*; public class Test { public static void main(String[] args){ ArrayList<Student> list = new ArrayList <>(); list.add(new Student("Peter", 65)); list.add(new Student("Jill", 50)); list.add(new Student("Sarah", 34)); Collections.sort(list); System.out.print(list + " "); Collections.sort(list., new StudentComparator1()); System.out.println(list); } static class StudentComparator 1 implements Comparator<Student> { public int compare(Student s1, Student s2){ return s1.name.compareTo(s2.name); } } static class Student implements Comparable<student> { String name; int age; Student(String name, int age){ this.name = name; this.age = age; } public int compareTo(Student s){ return this.age - s.age; } public String toString() { return "[" + name + "," + "age" + "]"; } } } a. [[Sarah, 34], [Jill, 50], [Peter, 65]] | [[Sarah, 34], [Jill, 50], [Peter, 65]] b. [[Jill, 50], [Peter, 65], [Sarah, 34]] | [[Jill, 50], [Peter, 65], [Sarah, 34]] c. [[Sarah, 34], [Jill, 50], [Peter, 65]] | [[Jill, 50], [Peter, 65], [Sarah, 34]] d. [[Jill, 50], [Peter, 65], [Sarah, 34]] | [[Sarah, 34], [Jill, 50], [Peter, 65]] e. None of the above. This program fails to compile.
c. c. [[Sarah, 34], [Jill, 50], [Peter, 65]] | [[Jill, 50], [Peter, 65], [Sarah, 34]]
30.) When a collision occurs during the insertion of an entry to a hash table, ______ finds the next available location sequentially. a. quadratic probic b. double hashing. c. linear probing d. Rehashing e. Separate chaining
c. linear probing
A wildcard type argument is denoted by a(n) __________. a. asterisk (*). b. underscore (_). c. question mark (?). d. caret (^).
c. question mark (?).
7.) You can use the methods in the Arrays class to a. find the maximum object in an array based on the compareTo method. b. find the maximum object in an array using a Comparator object. c. sort an array. d. shuffle an array. e. do a binary search on an array.
c. sort an array e. do a binary search on an array.
21.) Analyzing algorithm efficiency is ___. a. to measure their actual execution time. b. to estimate their execution time. c. to estimate their growth function. d. to estimate their complexity.
c. to estimate their growth function
Which is the following is the correct syntax to indicate Class A is a subclass of B? a) public class B extends A {......} b) public class A: super B {......} c) public class A {super (); ....} d) public class A extends B {......} e) public class A implements B( f) none of the above
d) public class A extends B {......}
__________ is the default upper bound of a type parameter. a. String. b. Comparable. c. Class. d. Object.
d. Object.
When a generic class is instantiated without specifying a type argument, it is said to have a __________. a. Empty type b. Dynamic Type c. Abstract Type d. Raw Type e. Static type
d. Raw Type
What is list after the following code is executed? ArrayList<Interger> list = new ArrayList<>(); list.add(1); list.add(2); list.add(3); list.add(4); list.add(5); list.remove(2); System.out.println(list): a. [1,2,3,4,5] b. [2,3,4,5] c. [1,3,4,5] d. [1,2,4,5] e. [1,2,3,5]
d. [1,2,4,5]
20.) Suppose set s1 is [1,2,5[ and set s2 is [2,3,6]. After s1.retainAll(s2), s1 is _____. a. [1,2,2,3,5,6] b. [1,2,3,5,6] c. [1,5] d. [2] e. None of the above
d. [2]
19.) The output of the following code is _______. LinkedHashSet<String> set1 - new LinkedHashSet<>(); set1.add("Memphis"); LinkedHashSet<String> set2 = set1; set1.add("Germantown"); set2.add("Kelowna"); set2.add("San Francisco"); System.out,println(set2); a. [Memphis] b. [Memphis, Germantown] c. [Kelowna, San Francisco] d. [Memphis, Germantown, Kelowna, San Francisco] e. [Memphis, San Francisco] f. Compiler error (cannot have set2 = set1, one has to copy the contents)
d. [Memphis, Germantown, Kelowna, San Francisco]
14.) Suppose your program frequently tests whether a student is in a soccer team, what is the best data structure to store the students in a soccer team? a. ArrayList b. LinkedHashSet c. TreeSet d. LinkedList e. HashSet
e. HashSet
11.) Which of the following data types does not implement the Collection interface? a. HashSet b. TreeSet c. ArrayList d. LinkedList e. Map
e. Map
One generic Stack class could be the basis for creating many Stack classes, e.g., Stack<Double>, Stack<Integer> and Stack<Employee>. These classes are known as __________. a. subclasses. b. generic subclasses. c. generic super classes d. generic type classes e. parameterized classes. f. Dynamic linked type classes
e. parameterized classes.
1.) The method header is left blank in the following code. Fill in the header. public class GenericMethodDemo{ public static void main(String[] args){ integer[] integers = {1,2,3,4,5}; String[] strings = {"London", "Paris", "New York", "Austin"}; print(integers); print(strings); } // "missing header here" ------------------------------(which header ???) { for (int i = 0; i < list.length; i++) System.out.print(list[i] + " "); System.out.println(); } } a. public static void print(integer[] list) b. public static void print(String[] list) c. public static void print(int[] list) d. public static void print(Object[] list) e. public static <E> void print(E[] list) f. public static <?> void print(E[] list)
e. public static <E> void print(E[] list) f. public static <?> void print(E[] list)
An instance of _________ describes system errors. If this type of error occurs, there is little you can do beyond notifying the user and trying to terminate the program gracefully.
error
24.) Which of the following statements are true? a. MyArrayList and MyLinkedList are two concrete implementations of MyList. b. MyArrayList is implemented using an array. The array is dynamically created. If the capacity of the array is exceeded, create a new larger array and copy all the elements from the current array to the new array. c. MyLinkedList is implemented using a linked structure. d. A linked structure consists of nodes. Each node is dynamically created to hold an element. All the nodes are linked together to form a list. e. MyAbstractList partially implements MyList. f. All of the above
f. All of the above
An ________ allows a program to walk through the collection and remove the elements from the collection. a. set b. Remove c. Stack d. List e. ArrayList f. Iterator
f. Iterator
What is the process of defining two or more methods within the same class that have the same name but different parameters declaration?
method overloading
Why do the following 2 lines of code compile but cause a runtime error? Number[] numberArray = new Integer[2]; numberArray[0] = new Double(1.5);
numberArray[0] is of the Integer type. It will be a casting error at runtime.
An exception is always an instance of ____ .
throwable
What is the output display of the following try-catch finally block codes? public class TryCatchFinally { public static void main(String[] args) { try { System.out.println("W"); try{ System.out.println("X"); throw new Exception("threw exception in X"); } finally { System.out.println("A"); } } catch (Exception e) { System.out.println("Y"); } finally { System.out.println("Z"); } System.out.println("A1"); } }
w x y A z A1
Write codes that will remove all the 'A' :
while(letters.contains("A")) letters.remove("A");
What is a Constructor of a class and what does it do?
• Constructors are a special kind of methods that are invoked to construct objects. • A constructor is automatically called when an instance of a class is created. • Constructors are used to perform operations at the time an object is created. • Constructors typically initialize instance fields and perform other object initialization tasks.