1.
Which statements are true about comparing two instances of the same class,given that the equals() and hashCode() methods have been properly overridden?
(choose all that apply)
Correct Answer(s)
B. If the equals()methood returns false,the hashCode() comparison==might return true.
D. If the hashCode() comparison==returns true,the equals() method might return true
E. If the hashCode() comparison!=returns true,the equals() method must return true
Explanation
If the equals() method returns false, it means that the two instances are not equal. In this case, the hashCode() comparison might still return true because the hashCode() method can generate the same hash code for different objects. This is known as a hash code collision.
If the hashCode() comparison returns true, it means that the hash codes of the two instances are the same. However, this does not guarantee that the instances are equal. The equals() method might still return true, but it is also possible for it to return false.
If the hashCode() comparison returns false, it means that the hash codes of the two instances are different. In this case, the equals() method must return true because different hash codes imply different objects.
2.
Which of the following most closely describes a bitset collection?
Correct Answer
D. A collection for storing bits as on-off information, like a vector of bits.
Explanation
A bitset collection is a data structure that is used to store and manipulate bits. It is similar to a vector of bits, where each bit can be either on or off. This collection is commonly used in scenarios where memory efficiency and manipulation of individual bits are important, such as in algorithms that involve bitwise operations or in situations where a large number of boolean values need to be stored compactly.
3.
Which most closely matches a java description of a java map
Correct Answer
D. An interface that ensures that implementing classes cannot contain duplicate keys.
Explanation
The correct answer is an interface that ensures that implementing classes cannot contain duplicate keys. This is because a Java map is a data structure that stores key-value pairs, and it does not allow duplicate keys. The interface mentioned in the answer ensures that any class implementing it will adhere to this rule of not allowing duplicate keys in the map.
4.
Which collection class(es)allows you to grow or shrink its size and provides indexed access to its elements,but whose methods are not synchronised??(choose all that aaply)
Correct Answer
D. Java.util.ArrayList
Explanation
The java.util.ArrayList class allows you to grow or shrink its size and provides indexed access to its elements. Its methods are not synchronized, meaning that they are not thread-safe. This allows for better performance in single-threaded environments but may lead to data corruption if accessed concurrently by multiple threads.
5.
The Enumeration interface allows a program to iterate its way through the elements of a container such as a Vector.
Correct Answer
A. True
Explanation
The Enumeration interface is used to iterate through the elements of a container, such as a Vector. It provides methods to check if there are more elements in the container and to retrieve the next element. Therefore, the statement that the Enumeration interface allows a program to iterate through the elements of a container like a Vector is true.
6.
The hashCode method is used by the java.util.SortedSet collection class to order the
elements within that set.
Correct Answer
B. False
Explanation
The explanation for the given answer is that the hashCode method is not used by the java.util.SortedSet collection class to order the elements within the set. The SortedSet interface in Java uses the compareTo method, not the hashCode method, to order its elements. The hashCode method is used for generating hash codes for objects in order to efficiently store and retrieve them from hash-based data structures like HashMap or HashSet.
7.
The hashCode method is used by the java.util.HashSet collection class to group the
elements within that set into hash buckets for swift retrieval.
Correct Answer
A. True
Explanation
The explanation for the given correct answer is that the hashCode method in Java is indeed used by the HashSet collection class to group elements into hash buckets. This allows for efficient retrieval of elements from the set based on their hash values.
8.
The hashCode method for a given class can be used to test for object inequality, but
NOT object equality, for that class.
Correct Answer
A. True
Explanation
The hashCode method in a class is used to generate a unique identifier for each object of that class. This identifier can be used to check if two objects are not equal, but it cannot be used to determine if two objects are equal. The reason for this is that multiple objects can have the same hash code, but they may still be different objects. Therefore, the hashCode method can only be used to test for object inequality, not object equality.
9.
Public static Collection get()
{
Collection sorted = new LinkedList();
sorted.add("B");
sorted.add("C");
sorted.add("A");
return sorted;
}
public static void main(String[] args)
{
for (Object obj: get())
{
System.out.print(obj + ", ");
}
}
What is the result?
Correct Answer
B. B,C,A
Explanation
The code will print "B, C, A" as the output. The get() method returns a LinkedList collection with elements "B", "C", and "A" in that order. The for-each loop in the main method iterates over each element in the collection and prints it followed by a comma. Therefore, the output will be "B, C, A".
10.
Properties method getProperty locates the value associated with the specified key. If the key is not found in this Properties object,getProperty attempts to locate the key in the default Properties object (if there is one).
Correct Answer
A. True
Explanation
The explanation for the given correct answer is that the Properties method getProperty is used to find the value associated with a specific key. If the key is not found in the current Properties object, the method will attempt to locate the key in the default Properties object, if one exists. Therefore, the statement is true.
11.
Import java.util.*;
public class TryMe {
public static void main(String args[]) {
Queue<String> q = new PriorityQueue<String>();
q.add("3");
q.add("1");
q.add("2");
System.out.print(q.poll() + " ");
System.out.print(q.peek() + " ");
System.out.print(q.peek());
}
}
Correct Answer
C. 1 2 2
Explanation
peek() - retrieves, but does not remove, the head of this queue, or returns null if this queue is empty.
poll() - retrieves and removes the head of this queue, or returns null if this queue is empty.
12.
Import java.util.*;
public class TestArrayList
{
public static void main(String args[])
{
List test =new ArrayList();
String s="hi";
testadd(s);
testadd(s+s);
System.out.println(test.size());
System.out.println(test.contains(42));
System.out.println(test.contains("hihi"));
test.remove("hi");
System.out.println(test.size());
}
}
What is the output of this program???
Correct Answer
A. 3 false true 2
Explanation
The output of this program is "3 false true 2". This is because the program first adds the string "hi" to the ArrayList, then adds the concatenation of "hi" with itself ("hihi") to the ArrayList. The size of the ArrayList is then printed, which is 2. The program then checks if the ArrayList contains the integer 42, which it does not, so it prints false. Next, it checks if the ArrayList contains the string "hihi", which it does, so it prints true. Finally, the program removes the string "hi" from the ArrayList, resulting in a size of 1, which is printed as 2.
13.
Import java.util.*;
public class WrappedString
{
private String s;
public WrappedString(String s)
{
this.s = s;
}
public static void main(String[] args)
{
HashSeths = new HashSet();
WrappedString ws1 = new WrappedString("aardvark");
WrappedString ws2 = new WrappedString("aardvark");
String s1 = new String("aardvark");
String s2 = new String("aardvark");
hs.add(ws1); hs.add(ws2); hs.add(s1); hs.add(s2);
System.out.println(hs.size());
}
}
What is the result?
Correct Answer
D. 3
Explanation
The result of the code is 3. This is because the HashSet only allows unique elements, and in this case, the HashSet will consider the two WrappedString objects (ws1 and ws2) as separate elements, even though they have the same value. Additionally, the two String objects (s1 and s2) will also be considered as separate elements. Therefore, the HashSet will have a total of 3 unique elements.
14.
Import java.util.*;
public class PQ
{
public static void main(String[] args)
{
PriorityQueue pq = new PriorityQueue();
pq.add("carrot");
pq.add("apple");
pq.add("banana");
System.out.println(pq.poll() + ":" + pq.peek());
}
}
What is the result?
Correct Answer
C. Apple:banana
Explanation
The code creates a PriorityQueue and adds three strings: "carrot", "apple", and "banana". The poll() method removes and returns the first element in the PriorityQueue, which is "apple". The peek() method returns the first element in the PriorityQueue without removing it, which is "banana". Therefore, the result is "apple:banana".
15.
Import java.util.*;
public class Example
{
public static void main(String[] args) {
// insert code here
set.add(new Integer(2));
set.add(new Integer(1));
System.out.println(set);
}
}
Which code, inserted at line 4, guarantees that this program will output [1, 2]?
Correct Answer
A. Set set = new TreeSet();
Explanation
The code "Set set = new TreeSet();" guarantees that this program will output [1, 2]. This is because TreeSet is an implementation of the Set interface that stores elements in sorted order. When elements are added to a TreeSet, they are automatically sorted based on their natural ordering or a custom comparator. In this case, the elements 2 and 1 are added to the TreeSet, and they will be sorted in ascending order, resulting in the output [1, 2].
16.
If you do not specify a capacity increment, the system will automatically add 2 to the size of the Vector each time additional capacity is needed.
Correct Answer
B. False
Explanation
If you do not specify a capacity increment, the system will not automatically add 2 to the size of the Vector each time additional capacity is needed. The default behavior of the Vector class is to double the size of the underlying array when additional capacity is required.
17.
How does the set collection deal with duplicate elements?
Correct Answer
B. The add method returns false if you attempt to add an element with a duplicate value.
Explanation
The add method in the set collection returns false if you try to add an element with a duplicate value. This means that if you try to add an element that already exists in the set, it will not be added and the method will return false to indicate that the addition was unsuccessful. This behavior allows the set collection to effectively deal with duplicate elements by not allowing them to be added in the first place.
18.
Given:
TreeSet map=new TreeSet();
map.add("one");
map.add("two");
map.add("three");
map.add("four");
map.add("one");
Iterator it=map.iterator();
while(it.hasNext()) {
System.out.println(it.next()+" ");
}
what is the result ???
Correct Answer
D. One two three four one
Explanation
The code creates a TreeSet named "map" and adds the strings "one", "two", "three", "four", and "one" to it. Since TreeSet does not allow duplicate elements, the second "one" is not added to the set. The code then creates an iterator named "it" and iterates over the elements in the set. The iterator returns the elements in ascending order, so the result will be "four one three two".
19.
Given:
import java.util.*
class AlgaeDiesel{
public static void main(String[] args) {
String sa={"foo","bar","baz" };
//insert method invocations here
}
}
what java.util.Arrays and/or java.util.Collections methods could you use
to convert sa to a List and then search the List to find the index
of the element whose valueis "foo"??(choose three methods)
Correct Answer(s)
A. Sort()
B. AsList()
G. BinarySearch()
Explanation
The correct answer is sort(), asList(), binarySearch(). The sort() method is used to sort the elements in the array in ascending order. The asList() method is used to convert the array to a List. The binarySearch() method is then used to search for the index of the element "foo" in the List.
20.
Given:
public static void search(List list)
{
list.clear();
list.add("b");
list.add("a");
list.add("c");
System.out.println(Collections.binarySearch(list, "a"));
}
What is the result of calling search with a valid List implementation?
Correct Answer
G. Result is undefined
Explanation
The result is undefined because the list is cleared before adding elements to it. The binarySearch method requires the list to be sorted in ascending order for accurate results. However, since the list is cleared before adding elements, it is not sorted and the behavior of the binarySearch method is unpredictable.
21.
Given:
ArrayList a = new ArrayList();
containing the values {“1”, “2”, “3”, “4”, “5”, “6”, “7”, “8”}
Which code will return 2?
Correct Answer
B. Comparator c = Collections.reverseOrder();
Collections.sort(a, c);
int result = Collections.binarySearch(a, “6”);
Explanation
The correct answer is the second option. By using the reverseOrder() method from the Collections class, the ArrayList is sorted in reverse order. Then, the binarySearch() method is used to find the index of the element "6" in the sorted ArrayList. Since "6" is the second element in the reversed sorted ArrayList, the result will be 2.
22.
Given:
public class Key {
private long id1;
private long id2;
// class Key methods
}
A programmer is developing a class Key, that will be used as a key in a
standard java.util.HashMap.Which two methods should be overridden to assure
that Key works correctly as a key? (Choose two.)
Correct Answer(s)
A. Public int hashCode()
D. Public boolean equals(Object o)
Explanation
To assure that Key works correctly as a key in a java.util.HashMap, the programmer should override the hashCode() method and the equals(Object o) method. The hashCode() method is used to generate a unique hash code for each Key object, which is used by the HashMap to determine the bucket in which to store the key-value pair. The equals(Object o) method is used to compare two Key objects for equality, allowing the HashMap to correctly retrieve the value associated with a given key.
23.
Given:
import java.util.*;
public class LetterASort
{
public static void main(String[] args)
{
ArrayList strings = new ArrayList();
strings.add("aAaA");
strings.add("AaA");
strings.add("aAa");
strings.add("AAaa");
Collections.sort(strings);
for (String s : strings) { System.out.print(s + " ");
}
}
}
What is the result?
Correct Answer
C. AAaa AaA aAa aAaA
Explanation
The code creates an ArrayList called "strings" and adds four strings to it. The strings are then sorted using the Collections.sort() method, which sorts the strings in lexicographic order. The sorted strings are then printed using a for-each loop. The output will be "AAaa AaA aAa aAaA" because the strings are sorted in lexicographic order, with uppercase letters appearing before lowercase letters.
24.
Given:
import java.util.*;
class Flubber
{
public static void main(String[] args)
{
List x=new ArrayList();
x.add("x");
x.add("xx");
x.add("Xx");
//insert code here
for(String s:x)
System.out.println(s);
}}
the output is:
xx
Xx
x
which code, inserted will produce the preceding output??
(choose al that apply)
Correct Answer
E. Comparator c=Collections.reverseOrder();
Collections.sort(x,c);
Explanation
The correct answer is "Comparator c=Collections.reverseOrder(); Collections.sort(x,c);". This code will sort the list "x" in reverse order using the Comparator interface and the reverseOrder() method from the Collections class. This will result in the output being printed in the order "xx", "Xx", and "x".
25.
Given the code. What is the result?
public class TrickyNum<X extends Number> {
private X x;
public TrickyNum(X x) {
this.x = x;
}
private double getDouble() {
return x.doubleValue();
}
public static void main(String args[]) {
TrickyNum<Integer> a = new TrickyNum<Integer>(new Integer(1));
System.out.print(a.getDouble());
}
}
Correct Answer
C. "1.0" is printed.
Explanation
The abstract class Number is the superclass of classes BigDecimal, BigInteger, Byte, Double, Float, Integer, Long, and Short.
26.
Given the code. What is the result?
public class TrickyNum<X extends Object> {
private X x;
public TrickyNum(X x) {
this.x = x;
}
private double getDouble() {
return ((Double) x).doubleValue();
}
public static void main(String args[]) {
TrickyNum<Integer> a = new TrickyNum<Integer>(new Integer(1));
System.out.print(a.getDouble());
}
}
Correct Answer
B. An exception is thrown at runtime.
Explanation
ClassCastException: Integer cannot be cast to Double.
27.
Given the code. What is the result?
public class TrickyNum<X extends Object> {
private X x;
public TrickyNum(X x) {
this.x = x;
}
private double getDouble() {
return x.doubleValue();
}
public static void main(String args[]) {
TrickyNum<Integer> a = new TrickyNum<Integer>(new Integer(1));
System.out.print(a.getDouble());
}
}
Correct Answer
A. Compilation fails.
Explanation
The method doubleValue() is undefined for the type X
28.
Given the code. What is the result?
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
public class TryMe {
public static void main(String args[]) {
List list = new LinkedList<String>();
list.add("one");
list.add("two");
list.add("three");
Collections.reverse(list);
Iterator iter = list.iterator();
for (Object o : iter) {
System.out.print(o + " ");
}
}
}
Correct Answer
D. Compilation fails
Explanation
The construction for(;) can only iterate over an array or an instance of java.lang.Iterable.
29.
Given the code. Select correct calls of methods. (Select all that apply)
import java.util.*;
class Empty {
}
class Extended extends Empty {
}
public class TryMe {
public static void doStuff1(List<Empty> list) {
// some code
}
public static void doStuff2(List list) {
// some code
}
public static void doStuff3(List extends Empty> list) {
// some code
}
public static void main(String args[]) {
List<Empty> list1 = new LinkedList<Empty>();
List<Extended> list2 = new LinkedList<Extended>();
// more code here
}
}
Correct Answer(s)
A. DoStuff1(list1);
B. DoStuff2(list2);
C. DoStuff2(list1);
D. DoStuff3(list1);
E. DoStuff3(list2);
Explanation
The correct calls of methods are doStuff1(list1), doStuff2(list2), doStuff2(list1), doStuff3(list1), and doStuff3(list2).
- doStuff1(list1) is a correct call because it matches the parameter type of List.
- doStuff2(list2) is a correct call because it accepts a raw List, and list2 is a List which is a subtype of List.
- doStuff2(list1) is a correct call because it also accepts a raw List, and list1 is a List.
- doStuff3(list1) is a correct call because it accepts a List that extends Empty, and list1 is a List.
- doStuff3(list2) is a correct call because it also accepts a List that extends Empty, and list2 is a List which is a subtype of List.
30.
Given a properly String array containing five elements,which range of results could a proper invocation of Arrays.binarySearch() produce???
Correct Answer
G. -6 through 4
31.
Given
public static void before()
{
Set set=new TreeSet();
set.add("2");
set.add(3);
set.add("1");
Iterator it=set.iterator();
while(it.hasNext())
Sytem.out.println(it.next()+" ");
}
which of the following statements are true??
Correct Answer
E. Before () method will throw an exception at runtime
Explanation
The before() method will throw an exception at runtime because the line "Sytem.out.println(it.next()+" ");" has a typo. It should be "System.out.println(it.next()+" ");" with a capital 'S' in System.
32.
Consider the following code snippets:
class GC2
{
public GC2 getIt(GC2 gc2)
{
return gc2;
}
public static void main(String a[])
{ GC2 g = GC2();
GC2 c = GC2();
c = g.getIt(c);
} }
How many objects are eligible for Garbage Collection?
Correct Answer
B. None of the objects are eligible
Explanation
The code snippet creates two objects of type GC2, named "g" and "c". The "getIt" method is called on object "g" passing object "c" as an argument. However, since the "getIt" method simply returns the object passed as an argument, there are no objects that become eligible for garbage collection in this code. Therefore, the correct answer is "none of the objects are eligible".
33.
Consider the following code snippet:
import java.util.*;
public class TestCol8
{
public static void main(String argv[])
{
TestCol8 junk = new TestCol8();
junk.sampleMap();
}
public void sampleMap()
{
TreeMap tm = new TreeMap();
tm.put("a","Hello");
tm.put("b","Java");
tm.put("c","World");
Iterator it = tm.keySet().iterator();
while(it.hasNext()){ System.out.print(it.next());
} } }
What will be the output of the above code snippet?
Correct Answer
A. Abc
Explanation
The code snippet creates a TreeMap object and adds three key-value pairs to it. Then, it retrieves the set of keys from the TreeMap and iterates over them using an iterator. The iterator's next() method is called in each iteration and the key is printed. Therefore, the output will be "abc".
34.
Consider the following code snippet:
import java.util.*;
public class TestCol3
{
public static void main(String[] args)
{
List l = new ArrayList();
l.add("One");
l.add("Two");
l.add("Three");
l.add("Four");
l.add("One");
l.add("Four");
Set h = new HashSet();
h.addAll(l);
System.out.println("Size:" + l.size() + h.size());
} }
What will be the output of the following code snippet?
Correct Answer
A. Size: 64
Explanation
The output of the code snippet will be "Size: 64". This is because the code first creates an ArrayList named "l" and adds six elements to it. Then, it creates a HashSet named "h" and adds all the elements from "l" to it. Since a HashSet does not allow duplicate elements, the duplicate elements "One" and "Four" will be removed. Finally, the code prints the size of "l" (6) and the size of "h" (4), resulting in the output "Size: 64".
35.
Class Stack in package java.util extends class LinkedList.
Correct Answer
B. False
Explanation
The given statement is false. The class Stack in package java.util does not extend the class LinkedList. In fact, the class Stack in java.util package is a subclass of the class Vector, not LinkedList. Therefore, the correct answer is False.
36.
A programmer has an algorithm that requires a java.util.List that
provides
an efficient implementation of add(0, object), but does NOT need to support
quick random access.
What supports these requirements?
Correct Answer
D. Java.util.LinkedList
Explanation
The java.util.LinkedList class supports the requirements mentioned in the question. It provides an efficient implementation of the add(0, object) method, which allows adding an element at the beginning of the list. It does not need to support quick random access, which means accessing elements by index may not be as efficient as in other list implementations like java.util.ArrayList. Therefore, java.util.LinkedList is the correct choice for the given requirements.
37.
Which of the following options give the names of data structures that can be
used for elements that have ordering, but no duplicates? (Choose 2)
Correct Answer(s)
A. SortedSet
B. TreeSet
Explanation
SortedSet and TreeSet are both data structures that can be used for elements that have ordering but no duplicates. SortedSet is an interface in Java that extends the Set interface and maintains the elements in ascending order. TreeSet is a class in Java that implements the SortedSet interface and stores elements in a sorted order using a binary search tree. Both data structures ensure that there are no duplicate elements in the collection while maintaining the order of the elements.
38.
Which of the following is the best-performing implementation of Set interface?
Correct Answer
A. HashSet
Explanation
HashSet is the best-performing implementation of the Set interface because it offers constant-time performance for basic operations like add, remove, and contains. It achieves this by using a hash table to store elements, which allows for efficient retrieval and insertion. TreeSet, on the other hand, is a sorted implementation of Set that offers logarithmic time complexity for these operations. HashTable is an older implementation that is now considered legacy, and LinkedHashSet maintains a linked list to preserve insertion order, which adds some overhead. SortedSet is not an implementation but rather an interface that is implemented by TreeSet.
39.
Consider the following code snippet:
import java.util.*;
public class TestCol4 {
public static void main(String[] args)
{ Set h = new HashSet();
h.add("One");
h.add("Two");
h.add("Three");
h.add("Four");
h.add("One");
h.add("Four");
List l = new ArrayList();
l.add("One");
l.add("Two");
l.add("Three");
h.retainAll(l);
System.out.println("Size:" + l.size() + h.size());
} }
What will be the output of the above code snippet?
Correct Answer
A. Size:33
Explanation
The output of the code snippet will be "size:33". This is because the HashSet "h" retains only the elements that are present in the ArrayList "l". Since both "One", "Two", and "Three" are common elements in both sets, they are retained in "h". Therefore, the size of "h" will be 3, and the size of "l" will also be 3.
40.
Which of the following options are true about abstract implementations in
Collections?(choose 3)
Correct Answer(s)
A. It provides static factory class
C. They provide hooks for custom implementations
D. All major interfaces are supported
Explanation
Abstract implementations in Collections provide a static factory class, which allows for the creation of instances of the abstract implementation. They also provide hooks for custom implementations, allowing developers to override certain methods and customize the behavior of the implementation. Additionally, all major interfaces are supported by abstract implementations, meaning that they can be used interchangeably with other implementations that adhere to the same interface.