1.
Given:
import java.util.*;class Test { public static void main(String[] args) { // insert code here x.add("one"); x.add("two"); x.add("TWO"); System.out.printIn(x.poll()); }}
Correct Answer
B. TreeSet x = new TreeSet();
Explanation
The correct answer is TreeSet x = new TreeSet(); because the code uses the poll() method, which is a method specific to the TreeSet class. This method retrieves and removes the first element from the TreeSet, and since it is called without any errors, it means that the variable x must be of type TreeSet.
2.
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);} }
And the output:
xxXx x
Which code, inserted at // insert code here, will produce the preceding output? (Choose all that apply.)
Correct Answer
B. Comparable c = Collections.reverse(); Collections.sort(x,c);
Explanation
The correct answer is "Comparable c = Collections.reverse(); Collections.sort(x,c);". This code will sort the elements in the list in reverse order and then print them out. The output "xxXx x" indicates that the elements "xx", "Xx", and "x" are sorted in reverse order.
3.
Given:
public static void main(String[] args) { // INSERT DECLARATION HERE for (int i = 0; i <= 10; i++) { List row = new ArrayList(); for (int j = 0; j <= 10; j++) row.add(i * j); table.add(row); } for (List row : table) System.out.println(row); }
Which statements could be inserted at // INSERT DECLARATION HERE to allow this code to compile and run? (Choose all that apply.)
Correct Answer
B. List table = new ArrayList();
Explanation
The correct answer is "List table = new ArrayList();". This statement declares a new variable named "table" of type List and initializes it with a new instance of the ArrayList class. This allows the code to create a table structure using nested ArrayLists and populate it with values.
4.
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() method returns false, the hashCode() comparison == might return true.
D. If the hashCode() comparison == returns true, the equals() method might return true.
Explanation
If the equals() method returns false, the hashCode() comparison == might return true. This is because two objects can have different values but still generate the same hash code. However, it is not guaranteed that the hashCode() comparison will always return true in this case.
If the hashCode() comparison == returns true, the equals() method might return true. This is because two objects can have the same hash code but still be different objects. The equals() method will further compare the actual values of the objects to determine if they are equal or not. Therefore, it is possible for the equals() method to return true even if the hashCode() comparison returns true.
5.
Given:
10. public static void main(String[] args) {11. Queue q = new LinkedList();12. q.add("Veronica");13. q.add("Wallace");14. q.add("Duncan");15. showAll(q);16. }17.18. public static void showAll(Queue q) {19. q.add(new Integer(42));20. while (!q.isEmpty ( ) )21. System.out.print(q.remove( ) + " ");22. }
What is the result?
Correct Answer
D. Veronica Wallace Duncan 42
Explanation
The code first adds three strings ("Veronica", "Wallace", "Duncan") to the queue. Then, the method showAll is called, which adds an Integer object with a value of 42 to the queue. The while loop then removes and prints each element in the queue until it is empty. Since the Integer object was added last, it will be the first element to be removed and printed. Therefore, the result will be "Veronica Wallace Duncan 42".
6.
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()) System.out.print(it.next() + " ");}
Which of the following statements are true?
Correct Answer
E. The before() method will throw an exception at runtime.
Explanation
The before() method will throw an exception at runtime because the TreeSet can only contain elements of the same type, but in this case, it contains both Strings and integers. Therefore, a ClassCastException will be thrown when trying to add an integer to the TreeSet.
7.
Given:
import java.util.*;class MapEQ { public static void main(String[] args) { Map m = new HashMap(); ToDos tl = new ToDos("Monday"); ToDos t2 = new ToDos("Monday"); ToDos t3 = new ToDos("Tuesday"); m.put(tl, "doLaundry"); m.put(t2, "payBills"); m.put(t3, "cleanAttic"); System.out.printIn(m.size()); }}class ToDos{ String day; ToDos(String d) { day = d; } public boolean equals(Object o) { return ((ToDos)o).day == this.day; } // public int hashCode() ( return 9; }}Which is correct? (Choose all that apply.)
Correct Answer(s)
C. As the code stands the output will be 3.
D. If the hashCode() method is uncommented the output will be 2.
Explanation
The code creates a HashMap object "m" and adds three key-value pairs to it. The keys are instances of the "ToDos" class and the values are strings. The "ToDos" class has a constructor that takes a string parameter and a equals() method that compares the "day" variable of two "ToDos" objects. Since "t1" and "t2" have the same "day" value, they are considered equal and only one of them will be added to the HashMap. However, "t3" has a different "day" value, so it will be added as a separate key-value pair. Therefore, the size of the HashMap will be 3. If the hashCode() method is uncommented, it will return a constant value of 9 for all "ToDos" objects. This will cause collisions in the HashMap and "t1" and "t2" will be considered different keys, resulting in a size of 2.
8.
Given:
12. public class AccountManager {13. private Map accountTotals = new HashMap();14. private int retirementFund;15.16. public int getBalance(String accountName) {17. Integer total = (Integer) accountTotals.get(accountName);18. if (total == null)19. total = Integer.valueOf(0);20. return total.intValue();21. }23. public void setBalance(String accountName, int amount) {24. accountTotals.put(accountName, Integer.valueOf(amount));25. }26. }
This class is to be updated to make use of
appropriate generic types, with no changes in behavior (for better or
worse). Which of these steps could be performed? (Choose three.)
Correct Answer(s)
B. Replace line 13 with
private Map accountTotals = new HashMap();
C. Replace lines 17-20 with
Integer total = accountTotals.get(accountName);
if (total == null)
total = 0;
return total;
E. Replace line 24 with
accountTotals.put(accountName, amount);
Explanation
The given class is currently using a raw type for the Map accountTotals. To update it to use appropriate generic types, we can replace line 13 with "private Map accountTotals = new HashMap();". This specifies that the keys are of type String and the values are of type Integer.
Additionally, we can replace lines 17-20 with "Integer total = accountTotals.get(accountName); if (total == null) total = 0; return total;". This simplifies the code by removing the unnecessary casting and valueOf() method calls.
Lastly, we can replace line 24 with "accountTotals.put(accountName, amount);". This removes the unnecessary casting of the amount to Integer.
9.
Given a properly prepared String array containing five elements, which range of results could a proper invocation of Arrays.binarysearch() produce?
Correct Answer
C. -6 through 4
10.
Given:
interface Hungry { void munch(E x); }interface Carnivore extends Hungry {}interface Herbivore extends Hungry {}abstract class Plant {}class Grass extends Plant {}abstract class Animal {}class Sheep extends Animal implements Herbivore { public void munch(Sheep x) {}}class Wolf extends Animal implements Carnivore { public void munch(Sheep x) {}}
Which of the following changes (taken separately) would allow this code to compile? (Choose all that apply.)
Correct Answer
D. Change the Herbivore interface to
interface Herbivore extends Hungry {}
Explanation
The code provided includes a class Sheep that implements the Herbivore interface. The Herbivore interface extends the Hungry interface, which has a method called munch. The Sheep class overrides this method with a parameter of type Sheep. The correct answer suggests changing the Herbivore interface to extend the Hungry interface, which would allow the Sheep class to implement the interface correctly. This change would ensure that the Sheep class overrides the munch method with the correct parameter type.
11.
Which collection class(es) allows you to grow or shrink its size and
provides indexed access to its elements, but whose methods are not
synchronized? (Choose all that apply.)
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 and can be accessed by multiple threads simultaneously, which can lead to inconsistencies if not properly synchronized. Therefore, java.util.ArrayList is the correct answer.
12.
Given:
import java.util.*;public class Group extends HashSet { public static void main(String[] args) { Group g = new Group () ; g.add(new Person("Hans")); g.add(new Person("Lotte")); g.add(new Person("Jane")); g.add(new Person("Hans")); g.add(new Person("Jane")); System.out. printIn ("Total: " + g.size() ); } public boolean add(Object o) { System.out.println("Adding: " + o) ; return super,add(o); }}class Person { private final String name; public Person(String name) { this.name = name; } public String toString() { return name; }}
Which of the following occur at least once when the code is compiled and run? (Choose all that apply.)
Correct Answer
D. The code does not compile.
Explanation
The code does not compile because the class "Group" is extending the "HashSet" class without specifying the type parameter. This results in a compilation error because the type parameter is required for the "HashSet" class.
13.
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 value is "foo" ? (Choose from one to three methods.)
Correct Answer(s)
A. Sort()
B. AsList()
E. BinarySearch()
Explanation
The correct answer is to use the methods sort(), asList(), and 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. Finally, the binarySearch() method is used to search for the index of the element "foo" in the List.
14.
Given that String implements java.lang.CharSequcnce, and:
import java.util.* ;public class LongWordFinder { public static void main(String [] args) { String[] array = { "123", "12345678", "1", "12", "1234567890"}; List list = Arrays.asList(array); Collection resultList = getLongWords(list); } // INSERT DECLARATION HERE { Collection longWords = new ArrayList(); for (E word : coll) if (word.length() > 6) longWords.add(word); return longWords; }}
Which declarations could be inserted at // INSERT DECLARATION HERE so that the program will compile and run? (Choose all that apply.)
Correct Answer
E. Static public Collection getLongWords(Collection coll)
Explanation
The declaration "static public Collection getLongWords(Collection coll)" could be inserted at // INSERT DECLARATION HERE so that the program will compile and run. This declaration specifies that the method "getLongWords" is a static method that returns a Collection and takes a parameter of type Collection. The access modifier "public" allows the method to be accessed from other classes. The keyword "static" means that the method belongs to the class itself, not an instance of the class.
15.
Given:
12. TreeSet map = new TreeSet();13. map.add("one");14. map.add("two");15. map.add("three");16. map.add("four"};17. map.add("one");18. Iterator it = map.iterator();19. while (it.hasNext() ) {20. System.out.print( it.next() + " " );21. }
What is the result?
Correct Answer
C. Four one three two
Explanation
The code will compile successfully and the output will be "four one three two". The TreeSet class in Java stores elements in sorted order and does not allow duplicates. In this code, the elements "one", "two", "three", and "four" are added to the TreeSet. Since "one" is added twice, it will be considered as a duplicate and only one instance of it will be stored in the set. The iterator is then used to iterate over the elements of the set and print them. The elements will be printed in the order they are stored in the set, which is "four", "one", "three", and "two".
16.
Given a method declared as:
public static List process(List nums)
A programmer wants to use this method like this:
// INSERT DECLARATIONS HEREoutput = process(input);
Which pairs of declarations could be placed at // INSERT DECLARATIONS HERE to allow the code to compile? (Choose all that apply.)
Correct Answer(s)
B. ArrayList input = null;
List output = null;
D. List input = null;
List output = null;
E. List input = null;
List output = null;
Explanation
The method process() accepts a List as a parameter and returns a List. Therefore, the input and output variables must be declared as List types. The first pair of declarations, ArrayList input = null; and List output = null;, is correct because ArrayList is a subclass of List, so it can be assigned to a List variable. The second pair of declarations, List input = null; and List output = null;, is also correct because they both are declared as List types.