Self Test


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());   } } 

Which, inserted at // insert code here, will compile? (Choose all that apply.)

  1. List<String> x = new LinkedList<String>();

  2. TreeSet<String> x = new TreeSet<String>();

  3. HashSet<String> x = new HashSet<String>();

  4. Queue<String> x = new PriorityQueue<String>();

  5. ArrayList<String> x = new ArrayList<String>();

  6. LinkedList<String> x = new LinkedList<String>();

image from book

2. 

Given:

 public static void main(String[] args) {   // INSERT DECLARATION HERE   for (int i = 0; i <= 10; i++) {     List<Integer> row = new ArrayList<Integer>();     for (int j = 0; j <= 10; j++)       row.add(i * j);     table.add(row);   }   for (List<Integer> 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.)

  1. List<List<Integer>> table = new List<List<Integer>>();

  2. List<List<Integer>> table = new ArrayList<List<Integer>>();

  3. List<List<Integer>> table = new ArrayList<ArrayList<Integer>>();

  4. List<List, Integer> table = new List<List, Integer>();

  5. List<List, Integer> table = new ArrayList<List, Integer>();

  6. List<List, Integer> table = new ArrayList<ArrayList, Integer>();

  7. None of the above.

image from book

3. 

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.)

  1. If the equals() method returns true, the hashCode() comparison == might return false.

  2. If the equals() method returns false, the hashCode() comparison == might return true.

  3. If the hashCode() comparison == returns true, the equals() method must return true.

  4. If the hashCode() comparison == returns true, the equals() method might return true.

  5. If the hashCode() comparison ! = returns true, the equals() method might return true.

image from book

4. 

Given:

 import java.util.*; class Flubber {   public static void main(String[] args) {     List<String> x = new ArrayList<String>();     x.add(" x"); x.add("xx"); x.add("Xx");     // insert code here    for(String s: x) System.out.println(s); } } 

And the output:

 xx Xx  x 

Which code, inserted at // insert code here, will produce the preceding output? (Choose all that apply.)

  1. Collections.sort(x);

  2. Comparable c = Collections.reverse(); Collections.sort(x,c);

  3. Comparator c = Collections.reverse(); Collections.sort(x,c);

  4. Comparable c = Collections.reverseOrder(); Collections.sort(x,c);

  5. Comparator c = Collections.reverseOrder(); Collections.sort(x,c);

image from book

5. 

Given:

 10.    public static void main(String[] args) { 11.        Queue<String> q = new LinkedList<String>(); 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?

  1. Veronica Wallace Duncan

  2. Veronica Wallace Duncan 42

  3. Duncan Wallace Veronica

  4. 42 Duncan Wallace Veronica

  5. Compilation fails.

  6. An exception occurs at runtime.

image from book

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?

  1. The before() method will print 1 2

  2. The before() method will print 1 2 3

  3. The before() method will print three numbers, but the order cannot be determined.

  4. The before() method will not: compile.

  5. The before() method will throw an exception at runtime.

image from book

7. 

Given:

 import java.util..*; class MapEQ {   public static void main(String[] args) {     Map<ToDos, String> m = new HashMap<ToDos, String>();     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.)

  1. As the code stands it will not compile.

  2. As the code stands the output will be 2.

  3. As the code stands the output will be 3.

  4. If the hashCode() method is uncommented the output will be 2.

  5. If the hashCode() method is uncommented the output will be 3.

  6. If the hashCode() method is uncommented the code will not compile.

image from book

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.)

  1. Replace line 13 with

     private Map<String, int> accountTotals = new HashMap<String, int>(); 

  2. Replace line 13 with

     private Map<String, Integer> accountTotals = new HashMap<String, Integer>(); 

  3. Replace line 13 with

     private Map<String<Integer>> accountTotals = new HashMap<String<Integer>>(); 

  4. Replace lines 17-20 with

     int total = accountTotals.get(accountName); if (total == null)     total = 0; return total; 

  5. Replace lines 17-20 with

     Integer total = accountTotals.get(accountName); if (total == null)     total = 0; return total; 

  6. Replace lines 17-20 with

     return accountTotals.get(accountName); 

  7. Replace line 24 with

     accountTotals.put(accountName, amount); 

  8. Replace line 24 with

     accountTotals.put(accountName, amount.intValue()); 

image from book

9. 

Given a properly prepared String array containing five elements, which range of results could a proper invocation of Arrays.binarysearch() produce?

  1. 0 through 4

  2. 0 through 5

  3. - 1 through 4

  4. -1 through 5

  5. - 5 through 4

  6. -5 through 5

  7. -6 through 4

  8. - 6 through 5

image from book

10. 

Given:

 interface Hungry<E> { void munch(E x); } interface Carnivore<E extends Animal> extends Hungry<E> {} interface Herbivore<E extends Plant> extends Hungry<E> {} abstract class Plant {} class Grass extends Plant {} abstract class Animal {} class Sheep extends Animal implements Herbivore<Sheep> {   public void munch(Sheep x) {} } class Wolf extends Animal implements Carnivore<Sheep> {   public void munch(Sheep x) {} } 

Which of the following changes (taken separately) would allow this code to compile? (Choose all that apply.)

  1. Change the Carnivore interface to

     interface Carnivore<E extends Plant> extends Hungry<E> {} 

  2. Change the Herbivore interface to

     interface Herbivore<E extends Animal> extends Hungry<E> {} 

  3. Change the Sheep class to

     class Sheep extends Animal implements Herbivore<Plant> {     public void munch(Grass x) {} } 

  4. Change the Sheep class to

     class Sheep extends Plant implements Carnivore<Wolf> {     public void munch(Wolf x) {} } 

  5. Change the Wolf class to

     class Wolf extends Animal implements Herbivore<Grass> {     public void munch(Grass x) {} } 

  6. No changes arc necessary.

image from book

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.)

  1. java.util.HashSet

  2. java.util.LinkedHashSet

  3. java.util.List

  4. java.util.ArrayList

  5. java.util.Vector

  6. java.util.PriorityQueue

image from book

12. 

Given:

 import java.util.*; public class Group extends HashSet<Person> {     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.)

  1. Adding Hans

  2. Adding Lotte

  3. Adding Jane

  4. Total: 3

  5. Total : 5

  6. The code does not compile.

  7. An exception is thrown at runtime.

image from book

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.)

  1. sort()

  2. asList()

  3. toList()

  4. search()

  5. sortList()

  6. contains()

  7. binarySearch()

image from book

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<String> list = Arrays.asList(array);         Collection<String> resultList = getLongWords(list);     }     // INSERT DECLARATION HERE     {         Collection<E> longWords = new ArrayList<E>();         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.)

  1. public static <E extends CharSequence> Collection<? extends CharSequence> getLongWords(Collection<E> coll)

  2. public static <E extends CharSequence> List<E> getLongWords(Collection<E> coll)

  3. public static Collection<E extends CharSequence> getLongWords(Collection<E> coll)

  4. public static List<CharSequence> getLongWords(Collection<CharSequence> coll)

  5. public static List<? extends CharSequence> getLongWords(Collection<? extends CharSequence> coll)

  6. static public <E extends CharSequence> Collection<E> getLongWords(Collection<E> coll)

  7. static public <E super CharSequence> Collection<E> getLongWords(Collection<E> coll)

image from book

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?

  1. Compilation fails.

  2. one two three four

  3. four three two one

  4. four one three two

  5. one two three four one

  6. one four three two one

  7. An exception is thrown at runtime.

  8. The print order is not guaranteed.

image from book

16. 

Given a method declared as:

 public static <E extends Number> List<? super E> process(List<E> nums) 

A programmer wants to use this method like this:

 // INSERT DECLARATIONS HERE output = process(input); 

Which pairs of declarations could be placed at // INSERT DECLARATIONS HERE to allow the code to compile? (Choose all that apply.)

  1. ArrayList<Integer> input = null;

    ArrayList<Integer> output = null;

  2. ArrayList<Integer> input = null;

    List<Integer> output = null;

  3. ArrayList<Integer> input = null;

    List<Number> output = null;

  4. List<Number> input = null;

    ArrayList<Integer> output = null;

  5. List<Number> input = null;

    List<Number> output = null;

  6. List<Integer> input = null;

    List<Integer> output = null;

  7. None of the above.

image from book

Answers

1. 

þ  

D and F are correct. The poll() method is associated with Queues. The LinkedList class implements the Queue interface.

ý  

A is incorrect because the List interface does not implement Queue, and the polymorphic instantiation would restrict x to invoking only those methods declared in the List interface, B, C, and E are incorrect, based on the above. (Objective 6.3)

2. 

þ  

B is correct.

ý  

A is incorrect because List is an interface, so you can't say new List() regardless of any generic types. D, E, and F are incorrect because List only takes one type parameter (a Map would take two, not a List), C is tempting, but incorrect. The type argument <List<integer>> must be the same for both sides of the assignment, even though the constructor new ArrayList() on the right side is a subtype of the declared type List on the left. (Objective 6.4)

3. 

þ  

B and D. B is true because often two dissimilar objects can return the same hashCode value. D is true because if the hashCode() comparison returns ==, the two objects might or might not be equal.

ý  

A, C, and E are incorrect. C is incorrect because the hashCode() method is very flexible in its return values, and often two dissimilar objects can return the same hash code value. A and E are a negation of the hashCode() and equals() contract. (Objective 6.2)

4. 

þ  

E is correct. Natural ordering would produce output in reverse sequence to that listed. The Collections.reverseOrder() method takes a Comparator not a Comparable to re-sort a Collection.

ý  

A, B, C, and D are incorrect based on the.above. (Objective 6.5)

5. 

þ  

B is correct, There is a compiler warning at line 19 because of an unchecked assignment, but other than that everything compiles and runs fine. Although q was originally declared as Queue<String>, in showAll() it's passed as an untyped Queue—nothing in the compiler or JVM prevents us from adding an Integer after that. The add() method puts things at the end of the queue, while remove() takes them from the beginning, so everything prints in the order they were put in.

ý  

A, C, D, E, and F are incorrect based on the above, (Objective 6.3)

6. 

þ  

E is correct. You can't put both Strings and ints into the same TreeSet. Without generics, the compiler has no way of knowing what type is appropriate for this TreeSet, so it allows everything to compile. At runtime, the TreeSet will try to sort the elements as they're added, and when it tries to compare an Integer with a String it will throw a ClassCastException. Note that although the before() method does not use generics, it does use autoboxing. Watch out for code that uses some new features and some old features mixed together.

ý  

A, B, C, and D are incorrect based on the above. (Objective 6.5)

7. 

þ  

C and D are correct. If hashCode() is not overridden then every entry will go into its own bucket, and the overridden equals() method will have no effect on determining equivalency. If hashCode() is overridden, then the overridden equals() method will view t1 and t2 as duplicates.

ý  

A, B, E, and F are incorrect based on the above, (Objective 6.2)

8. 

þ  

B, E, and G are correct.

ý  

A is wrong because you can't use a primitive type as a type parameter. C is wrong because a Map takes two type parameters separated by a comma. D is wrong because an int can't autobox to a null, and F is wrong because a null can't unbox to 0. H is wrong because you can't autobox a primitive just by trying to invoke a method with it. (Objective 6.4)

9. 

þ  

G is correct. If a match is found, binarysearch() will return the index of the element that was matched. If no match is found, binarysearch() will return a negative number that, if inverted and then decremented, gives you the insertion point. (array index) at which the value searched on should be inserted into the array to maintain a proper sort.

ý  

A, B, C, D, E, F, and H are incorrect based on the above. (Objective 6.5)

10. 

þ  

B is correct. The problem with the original code is that Sheep tries to implement Herbivore<Sheep> and Herbivore declares that its type parameter E can be any type that extends Plant. Since a Sheep is not a Plant, Herbivore<Sheep> makes no sense—the type Sheep is outside the allowed range of Herbivore's parameter E. Only solutions that either alter the definition of a Sheep or alter the definition of Herbivore will be able to fix this. So A, E, and F are eliminated. B works, changing the definition of an Herbivore to allow it to eat Sheep solves the problem. C doesn't work because an Herbivore<Plant> must have a munch (Plant) method, not munch(Grass). And D doesn't work, because in D we made Sheep extend Plant, now the Wolf class breaks because its munch (Sheep) method no longer fulfills the contract of Carnivore.(Objective 6.4)

11. 

þ  

D is correct. All of the collection classes allow you to grow or shrink the size of your collection. ArrayList provides an index to its elements, The newer collection classes tend not to have synchronized methods. Vector is an older implementation of ArrayList functionality and has synchronized methods; it is slower than ArrayList.

ý  

A, B, C, E, and F are incorrect based on the logic described above; Notes: C, List is an interface, and F, PriorityQueue does not offer access by index, (Objective 6.1)

12. 

þ  

F is correct. The problem here is in Group's add() method—it should have been add(Person), since the class extends HashSet<Person>. So this doesn't compile, Pop Quiz: What would happen if you fixed this code, changing add(Object) to add(Person)? Try running the code to see if the results match what you thought.

ý  

A, B, C, D, E, and G are incorrect based on the above. (Objective 6.4)

13. 

þ  

A, B, and G are required. The as List(), method converts an array to a List. You can find the index of an element in a List with the binarySearch() method, but before you do that you must sort the list using sort().

ý  

F is incorrect because contains() returns a boolean, not an index. C, D, and E are incorrect, because these methods are not defined in the List interface. (Objective 6.5)

14. 

þ  

F is correct.

ý  

A is close, but it's wrong because the return value is too vague. The last line of the method expects the return value to be Collection<String>, not Collection<?extendsCharSequence>. B is wrong because longWords has been declared as a Collection<E>, and that can't be implicitly converted to a List<E> to match the declared return value. (Even though we know that longWords is really an ArrayList<E>, the compiler only knows what it's been declared as.) C, D, and E are wrong because they do not declare a type variable E (there's no <> before the return value) so the getLongWords() method body will not compile. G is wrong because E super CharSequence makes no sense—super could be used in conjunction with a wildcard but not a type variable like E. (Objective 6.3)

15. 

þ  

D is correct. TreeSet assures no duplicate entries; also, when it is accessed it will return elements in natural order, which, for Strings means alphabetical.

ý  

A, B, C, E, F, G, and H are incorrect based on the logic described above. Note, even though as of Java 5 you don't have to use an Iterator, you still can, (Objective 6.5)

16. 

þ  

B, E, and F are correct.

ý  

The return type of process is definitely declared as a List, not an ArrayList, so A and D are wrong. C is wrong because the return type evaluates to List<Integer>, and that can't be assigned to a variable of type List<Number>. Of course all these would probably cause a NullPointerException since the variables are still null—but the question only asked us to get the code to compile. (Objective 6.4)




SCJP Sun Certified Programmer for Java 5 Study Guide Exam 310-055
SCJP Sun Certified Programmer for Java 5 Study Guide (Exam 310-055) (Certification Press)
ISBN: 0072253606
EAN: 2147483647
Year: 2006
Pages: 131

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net