Pages

Aug 25, 2012

Exercise-7 (Collections and Generics)



1. 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.)
A. List<List<Integer>> table = new List<List<Integer>>();
B. List<List<Integer>> table = new ArrayList<List<Integer>>();
C. List<List<Integer>> table = new ArrayList<ArrayList<Integer>>();
D. List<List, Integer> table = new List<List, Integer>();
E. List<List, Integer> table = new ArrayList<List, Integer>();
F. List<List, Integer> table = new ArrayList<ArrayList, Integer>();
G. None of the above
Answer:
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)

2. 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.)
A. If the equals() method returns true, the hashCode() comparison == might return false
B. If the equals() method returns false, the hashCode() comparison == might return true
C. If the hashCode() comparison == returns true, the equals() method must 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 might return true
Answer:
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)

3. 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 statements are true?
A. The before() method will print 1 2
B. The before() method will print 1 2 3
C. The before() method will print three numbers, but the order cannot be determined
D. The before() method will not compile
E. The before() method will throw an exception at runtime
Answer:
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)

4. Given:
import java.util.*;
class MapEQ {
public static void main(String[] args) {
Map<ToDos, String> m = new HashMap<ToDos, String>();
ToDos t1 = new ToDos("Monday");
ToDos t2 = new ToDos("Monday");
ToDos t3 = new ToDos("Tuesday");
m.put(t1, "doLaundry");
m.put(t2, "payBills");
m.put(t3, "cleanAttic");
System.out.println(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.)
A. As the code stands it will not compile
B. As the code stands the output will be 2
C. As the code stands the output will be 3
D. If the hashCode() method is uncommented the output will be 2
E. If the hashCode() method is uncommented the output will be 3
F. If the hashCode() method is uncommented the code will not compile
Answer:
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)

5. Given:
public class AccountManager {
private Map accountTotals = new HashMap(); //line 13
private int retirementFund;

public int getBalance(String accountName) {
Integer total = (Integer) accountTotals.get(accountName);  // line 17
if (total == null)
total = Integer.valueOf(0);
return total.intValue();   // line 20
}
public void setBalance(String accountName, int amount) {
accountTotals.put(accountName, Integer.valueOf(amount)); // line 24
} }
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.)
A. Replace line 13 with private
Map<String, int> accountTotals = new HashMap<String, int>();
B. Replace line 13 with private
Map<String, Integer> accountTotals = new HashMap<String, Integer>();
C. Replace line 13 with
private Map<String<Integer>> accountTotals = new HashMap<String<Integer>>();
D. Replace lines 17-20 with
int total = accountTotals.get(accountName);
if (total == null) total = 0;
return total;
E. Replace lines 17-20 with
Integer total = accountTotals.get(accountName);
if (total == null) total = 0; return total;
F. Replace lines 17-20 with return accountTotals.get(accountName);
G. Replace line 24 with accountTotals.put(accountName, amount);
H. Replace line 24 with accountTotals.put(accountName, amount.intValue());
Answer:
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)

6. 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.)
A. Change the Carnivore interface to
interface Carnivore<E extends Plant> extends Hungry<E> {}
B. Change the Herbivore interface to
interface Herbivore<E extends Animal> extends Hungry<E> {}
C. Change the Sheep class to
class Sheep extends Animal implements Herbivore<Plant> {
public void munch(Grass x) {}
}
D. Change the Sheep class to
class Sheep extends Plant implements Carnivore<Wolf> {
public void munch(Wolf x) {}
}
E. Change the Wolf class to
class Wolf extends Animal implements Herbivore<Grass> {
public void munch(Grass x) {}
}
F. No changes are necessary

Answer:
B is correct. The problem with the original code is that Sheep tries to implement HerbivoresSheep> 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)

7. 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.)
A. java.util.HashSet
B. java.util.LinkedHashSet
C. java.util.List
D. java.util.ArrayList
E. java.util.Vector
F. java.util.PriorityQueue
Answer:
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)

8. Given a method declared as
public static <E extends Number> List<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.)
A. ArrayList<Integer> input = null; ArrayList<Integer> output = null;
B. ArrayList<Integer> input = null; List<Integer> output = null;
C. ArrayList<Integer> input = null; List<Number> output = null;
D. List<Number> input = null; ArrayList<Integer> output = null;
E. List<Number> input = null; List<Number> output = null;
F. List<Integer> input = null; List<Integer> output = null;
G. None of the above
Answer:
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)

9. Given the proper import statement(s), and
PriorityQueue<String> pq = new PriorityQueue<String>();
pq.add("2");
pq.add("4");
System.out.print(pq.peek() + " ");
pq.offer("1");
pq.add("3");
pq.remove("1");
System.out.print(pq.poll() + " ");
if(pq.remove("2")) System.out.print(pq.poll() + " ");
System.out.println(pq.poll() + " " + pq.peek());
What is the result?
A. 2 2 3 3
B. 2 2 3 4
C. 4 3 3 4
D. 2 2 3 3 3
E. 4 3 3 3 3
F. 2 2 3 3 4
G. Compilation fails
H. An exception is thrown at runtime
Answer:
B is correct. For the sake of the exam, add() and offer() both add to (in this case), naturally sorted queues. The calls to poll() both return and then remove the first item from the queue, so the if test fails.
A, C, D, E, F, G, and H are incorrect based on the above. (Objective 6.1)

10. Given:
import java.util.*;
public class Mixup {
public static void main(String[] args) {
Object o = new Object();
// insert code here   line 7
s.add("o");
s.add(o);
}
}
And these three fragments:
I. Set s = new HashSet();
II. TreeSet s = new TreeSet();
III. LinkedHashSet s = new LinkedHashSet();
When fragments I, II, or III are inserted, independently, at line 7, which are true? (Choose all that apply.)

A. Fragment I compiles
B. Fragment II compiles
C. Fragment III compiles
D. Fragment I executes without exception
E. Fragment II executes without exception
F. Fragment III executes without exception
Answer:
A, B, C, D, and F are all correct.
Only E is incorrect. Elements of a TreeSet must in some way implement Comparable. (Objective 6.1)

11. Given:
import java.util.*;
class Turtle {
int size;
public Turtle(int s) { size = s; }
public boolean equals(Object o) { return (this.size == ((Turtle)o).size); }
// insert code here line 8
}
public class TurtleTest {
public static void main(String[] args) {
LinkedHashSet<Turtle> t = new LinkedHashSet<Turtle>();
t.add(new Turtle(1)); t.add(new Turtle(2)); t.add(new Turtle(1));
System.out.println(t.size());
}
}
And these two fragments:
I. public int hashCode() { return size/5; }
II. // no hashCode method declared
If fragment I or II is inserted, independently, at line 8, which are true? (Choose all that apply.)

A. If fragment I is inserted, the output is 2
B. If fragment I is inserted, the output is 3
C. If fragment II is inserted, the output is 2
D. If fragment II is inserted, the output is 3
E. If fragment I is inserted, compilation fails
F. If fragment II is inserted, compilation fails
Answer:
A and D are correct. While fragment II wouldn't fulfill the hashCode() contract (as you can see by the results), it is legal Java. For the purpose of the exam, if you don't override hashCode(), every object will have a unique hashcode.
B, C, E, and F are incorrect based on the above. (Objective 6.2)

12. Given the proper import statement(s), and:
TreeSet<String> s = new TreeSet<String>();
 TreeSet<String> subs = new TreeSet<String>();
s.add("a"); s.add("b"); s.add("c"); s.add("d"); s.add("e");

subs = (TreeSet)s.subSet("b", true, "d", true);
s.add("g");
s.pollFirst();
s.pollFirst();
s.add("c2");
System.out.println(s.size() +" "+ subs.size());
Which are true? (Choose all that apply.)
A. The size of s is 4
B. The size of s is 5
C. The size of s is 7
D. The size of subs is 1
E. The size of subs is 2
F. The size of subs is 3
G. The size of subs is 4
H. An exception is thrown at runtime
Answer:
B and F are correct. After "g" is added, TreeSet s contains six elements and TreeSet subs contains three (b, c, d), because "g" is out of the range of subs. The first pollFirst() finds and removes only the "a". The second pollFirst() finds and removes the "b" from both TreeSets (remember they are backed). The final add() is in range of both TreeSets. The final contents are [c,c2,d,e,g] and [c,c2,d].
A, C, D, E, G, and H are incorrect based on the above. (Objective 6.3)

13. Given:
import java.util.*;
public class Magellan {
public static void main(String[] args) {
TreeMap<String, String> myMap = new TreeMap<String, String>();
myMap.put("a", "apple"); myMap.put("d", "date");
myMap.put("f", "fig"); myMap.put("p", "pear");
System.out.println("1st after mango: " + // sop 1
myMap.higherKey("f"));
System.out.println("1st after mango: " + // sop 2
myMap.ceilingKey("f"));
System.out.println("1st after mango: " + // sop 3
myMap.floorKey("f"));
SortedMap<String, String> sub = new TreeMap<String, String>();
sub = myMap.tailMap("f");
System.out.println("1st after mango: " + // sop 4
sub.firstKey());
}
}
Which of the System.out.println statements will produce the output 1st after mango: p? (Choose all that apply.)
A. sop 1
B. sop 2
C. sop 3
D. sop 4
E. None; compilation fails
F. None; an exception is thrown at runtime
Answer:
A is correct. The ceilingKey() method's argument is inclusive. The floorKey() method would be used to find keys before the specified key. The firstKey() method's argument is also inclusive.
B, C, D, E, and F are incorrect based on the above. (Objective 6.3)

14. Given:
import java.util.*;
class Business { }
class Hotel extends Business { }
class Inn extends Hotel { }
public class Travel {
ArrayList<Hotel> go() {
// insert code here  line 9
}
}
Which, inserted independently at line 9, will compile? (Choose all that apply.)
A. return new ArrayList<Inn>();
B. return new ArrayList<Hotel>();
C. return new ArrayList<Object>();
D. return new ArrayList<Business>();
Answer:
B is correct.
A is incorrect because polymorphic assignments don't apply to generic type parameters. C and D are incorrect because they don't follow basic polymorphism rules. (Objective 6.4)

15. Given:
import java.util.*;
class Dog { int size; Dog(int s) { size = s; } }
public class FirstGrade {
public static void main(String[] args) {
TreeSet<Integer> i = new TreeSet<Integer>();
TreeSet<Dog> d = new TreeSet<Dog>();
d.add(new Dog(1)); d.add(new Dog(2)); d.add(new Dog(1));
i.add(1); i.add(2); i.add(1);
System.out.println(d.size() + " " + i.size());
}
}
What is the result?
A. 1 2
B. 2 2
C. 2 3
D. 3 2
E. 3 3
F. Compilation fails
G. An exception is thrown at runtime
Answer:
G is correct. Class Dog needs to implement Comparable in order for a TreeSet (which keeps its elements sorted) to be able to contain Dog objects.
A, B, C, D, E, and F are incorrect based on the above. (Objective 6.5)

16. Given:
import java.util.*;
public class GeoCache {
public static void main(String[] args) {
String[] s = {"map", "pen", "marble", "key"};
Othello o = new Othello();
Arrays.sort(s,o);
for(String s2: s) System.out.print(s2 + " ");
System.out.println(Arrays.binarySearch(s, "map"));
}
static class Othello implements Comparator<String> {
public int compare(String a, String b) { return b.compareTo(a); }
}
}
Which are true? (Choose all that apply.)
A. Compilation fails
B. The output will contain a 1
C. The output will contain a 2
D. The output will contain a -1
E. An exception is thrown at runtime
F. The output will contain "key map marble pen"
G. The output will contain "pen marble map key"
Answer:
D and G are correct. First, the compareTo() method will reverse the normal sort. Second, the sort() is valid. Third, the binarySearch() gives -1 because it needs to be invoked using the same Comparator (o), as was used to sort the array. Note that when the binarySearch() returns an "undefined result" it doesn't officially have to be a -1, but it usually is, so if you selected only G, you get full credit!
A, B, C, E, and F are incorrect based on the above. (Objective 6.5)


regards,
TechDexters Support Team
Hyderabad.


for Feedback and Support simply drop a mail in
techdexters{at}gmail.com
Remember to replace the {at} with @ in the email addresses

Aug 21, 2012

Collections and Generics




Overriding hashCode() and equals() (Objective 6.2)
  1. equals(), hashCode(), and toString() are public.
  2. Override toString() so that System.out.println() or other
  3. methods can see something useful, like your object's state.
  4. Use == to determine if two reference variables refer to the same object.
  5. Use equals() to determine if two objects are meaningfully equivalent.
  6. If you don't override equals(), your objects won't be useful hashing keys.
  7. If you don't override equals(), different objects can't be considered equal.
  8. Strings and wrappers override equals() and make good hashing keys.
  9. When overriding equals(), use the instanceof operator to be sure you're evaluating an appropriate class.
  10. When overriding equals(), compare the objects' significant attributes.
  11. Highlights of the equals() contract:
    1. Reflexive: x.equals(x) is true.
    2. Symmetric: If x.equals(y) is true, then y.equals(x) must be true.
    3. Transitive: If x.equals(y) is true, and y.equals(z) is true,
    4. then z.equals(x) is true.
    5. Consistent: Multiple calls to x.equals(y) will return the same result.
    6. Null: If x is not null, then x.equals(null) is false.
  12. If x.equals(y) is true, then x.hashCode() == y.hashCode() is true.
  13. If you override equals(), override hashCode().
  14. HashMap, HashSet, Hashtable, LinkedHashMap, & LinkedHashSet use hashing.
  15. An appropriate hashCode() override sticks to the hashCode() contract.
  16. An efficient hashCode() override distributes keys evenly across its buckets.
  17. An overridden equals() must be at least as precise as its hashCode() mate.
  18. To reiterate: if two objects are equal, their hashcodes must be equal.
  19. It's legal for a hashCode() method to return the same value for all instances (although in practice it's very inefficient).
  20. Highlights of the hashCode() contract:
    1. Consistent: multiple calls to x.hashCode() return the same integer.
    2. If x.equals(y) is true, x.hashCode() == y.hashCode() is true.
    3. If x.equals(y) is false, then x.hashCode() == y.hashCode() can be either true or false, but false will tend to create better efficiency.
  21. transient variables aren't appropriate for equals() and hashCode().
Collections (Objective 6.1)
  1. Common collection activities include adding objects, removing objects, verifying object inclusion, retrieving objects, and iterating.
  2. Three meanings for "collection":
    1. collection Represents the data structure in which objects are stored 
    2. Collection java.util interface from which Set and List extend
    3. Collections A class that holds static collection utility methods
  3. Four basic flavors of collections include Lists, Sets, Maps, Queues:
    1. Lists of things Ordered, duplicates allowed, with an index.
    2. Sets of things May or may not be ordered and/or sorted; duplicates not allowed.
    3. Maps of things with keys May or may not be ordered and/or sorted; duplicate keys are not allowed.
    4. Queues of things to process Ordered by FIFO or by priority.
  4. Four basic sub-flavors of collections Sorted, Unsorted, Ordered, Unordered.
    1. Ordered Iterating through a collection in a specific, non-random order.
    2. Sorted Iterating through a collection in a sorted order.
  5. Sorting can be alphabetic, numeric, or programmer-defined.

Key Attributes of Common Collection Classes (Objective 6.1)
  1. ArrayList: Fast iteration and fast random access.
  2. Vector: It's like a slower ArrayList, but it has synchronized methods.
  3. LinkedList: Good for adding elements to the ends, i.e., stacks and queues.
  4. HashSet: Fast access, assures no duplicates, provides no ordering.
  5. LinkedHashSet: No duplicates; iterates by insertion order.
  6. TreeSet: No duplicates; iterates in sorted order.
  7. HashMap: Fastest updates (key/values); allows one null key, many null values.
  8. Hashtable: Like a slower HashMap (as with Vector, due to its synchronized methods). No null values or null keys allowed.
  9. LinkedHashMap: Faster iterations; iterates by insertion order or last accessed; allows one null key, many null values.
  10. TreeMap: A sorted map.
  11. PriorityQueue: A to-do list ordered by the elements' priority.

Using Collection Classes (Objective 6.3)
  1. Collections hold only Objects, but primitives can be autoboxed.
  2. Iterate with the enhanced for, or with an Iterator via hasNext() & next().
  3. hasNext() determines if more elements exist; the Iterator does NOT move.
  4. next() returns the next element AND moves the Iterator forward.
  5. To work correctly, a Map's keys must override equals() and hashCode().
  6. Queues use offer() to add an element, poll() to remove the head of the queue, and peek() to look at the head of a queue.
  7. As of Java 6 TreeSets and TreeMaps have new navigation methods like floor() and higher().
  8. You can create/extend "backed" sub-copies of TreeSets and TreeMaps.

Sorting and Searching Arrays and Lists (Objective 6.5)
  1. Sorting can be in natural order, or via a Comparable or many Comparators.
  2. Implement Comparable using compareTo(); provides only one sort order.
  3. Create many Comparators to sort a class many ways; implement compare().
  4. To be sorted and searched, a List's elements must be comparable.
  5. To be searched, an array or List must first be sorted.

Utility Classes: Collections and Arrays (Objective 6.5)
  1. Both of these java.util classes provide
    1. A sort() method. Sort using a Comparator or sort using natural order.
    2. A binarySearch() method. Search a pre-sorted array or List
    3. Arrays.asList() creates a List from an array and links them together.
    4. Collections.reverse() reverses the order of elements in a List.
    5. Collections.reverseOrder() returns a Comparator that sorts in reverse.
    6. Lists and Sets have a toArray() method to create arrays.

Generics (Objective 6.4)
  1. Generics let you enforce compile-time type safety on Collections (or other classes and methods declared using generic type parameters).
  2. An ArrayList<Animal> can accept references of type Dog, Cat, or any other subtype of Animal (subclass, or if Animal is an interface, implementation).
  3. When using generic collections, a cast is not needed to get (declared type) elements out of the collection. With non-generic collections, a cast is required:
    List<String> gList = new ArrayList<String>();
    List list = new ArrayList();
    // more code
    String s = gList.get(0); // no cast needed
    String s = (String)list.get(0); // cast required
  4. You can pass a generic collection into a method that takes a non-generic collection, but the results may be disastrous. The compiler can't stop the method from inserting the wrong type into the previously type safe collection.
  5. If the compiler can recognize that non-type-safe code is potentially endangering something you originally declared as type-safe, you will get a compiler warning. For instance, if you pass a List<String> into a method declared as
     void foo(List aList) { aList.add(anInteger); }
    You'll get a warning because add() is potentially "unsafe".
  6. "Compiles without error" is not the same as "compiles without warnings." A compilation warning is not considered a compilation error or failure.
  7. Generic type information does not exist at runtime—it is for compile-time safety only. Mixing generics with legacy code can create compiled code that may throw an exception at runtime.
  8. Polymorphic assignments applies only to the base type, not the generic type parameter. You can say
    List<Animal> aList = new ArrayList<Animal>(); // yes
    You can't say
    List<Animal> aList = new ArrayList<Dog>(); // no
  9. The polymorphic assignment rule applies everywhere an assignment can be made. The following are NOT allowed:
    void foo(List<Animal> aList) { } // cannot take a List<Dog>
    List<Animal> bar() { } // cannot return a List<Dog>
  10. Wildcard syntax allows a generic method, accept subtypes (or supertypes) of the declared type of the method argument:
    void addD(List<Dog> d) {} // can take only <Dog>
    void addD(List<? extends Dog>) {} // take a <Dog> or <Beagle>
  11. The wildcard keyword extends is used to mean either "extends" or "implements." So in <? extends Dog>, Dog can be a class or an interface.
  12. When using a wildcard, List<? extends Dog>, the collection can be accessed but not modified.
  13. When using a wildcard, List<?>, any generic type can be assigned to the reference, but for access only, no modifications.
  14. List<Object> refers only to a List<Object>, while List<?> or List<? extends Object> can hold any type of object, but for access only.
  15. Declaration conventions for generics use T for type and E for element:
    public interface List<E> // API declaration for List
    boolean add(E o) // List.add() declaration
  16. The generics type identifier can be used in class, method, and variable declarations:
    class Foo<t> { } // a class
    T anInstance; // an instance variable
    Foo(T aRef) {} // a constructor argument
    void bar(T aRef) {} // a method argument
    T baz() {} // a return type
  17. The compiler will substitute the actual type.
  18. You can use more than one parameterized type in a declaration:

    public class UseTwo<T, X> { }
  19. You can declare a generic method using a type not defined in the class:

    public <T> void makeList(T t) { }

    is NOT using T as the return type. This method has a void return type, but to use T within the method's argument you must declare the <T>, which happens before the return type.

regards,
TechDexters Support Team
Hyderabad.


for Feedback and Support simply drop a mail in
techdexters{at}gmail.com
Remember to replace the {at} with @ in the email addresses

Aug 17, 2012

OCJP Exercise -6 (Strings)



1. Given:
import java.util.regex.*;
class Regex2 {
public static void main(String[] args) {
Pattern p = Pattern.compile(args[0]);
Matcher m = p.matcher(args[1]);
boolean b = false;
while(b = m.find()) {
System.out.print(m.start() + m.group());
}
}
}
And the command line:
java Regex2 "\d*" ab34ef
What is the result?
A. 234
B. 334
C. 2334
D. 0123456
E. 01234456
F. 12334567
G. Compilation fails
Answer:
E is correct. The \d is looking for digits. The * is a quantifier that looks for 0 to many occurrences of the pattern that precedes it. Because we specified *, the group() method returns empty Strings until consecutive digits are found, so the only time group() returns a value is when it returns 34 when the matcher finds digits starting in position 2. The start() method returns the starting position of the previous match because, again, we said find 0 to many occurrences.
A, B, C, D, F, and G are incorrect based on the above. (Objective 3.5)

2. Given:
import java.io.*;
class Player {
Player() { System.out.print("p"); }
}
class CardPlayer extends Player implements Serializable {
CardPlayer() { System.out.print("c"); }
public static void main(String[] args) {
CardPlayer c1 = new CardPlayer();
try {
FileOutputStream fos = new FileOutputStream("play.txt");
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(c1);
os.close();
FileInputStream fis = new FileInputStream("play.txt");
ObjectInputStream is = new ObjectInputStream(fis);
CardPlayer c2 = (CardPlayer) is.readObject();
is.close();
} catch (Exception x ) { }
}
}
What is the result?
A. pc
B. pcc
C. pcp
D. pcpc
E. Compilation fails
F. An exception is thrown at runtime
Answer:
C is correct. It's okay for a class to implement Serializable even if its superclass doesn't. However, when you deserialize such an object, the non-serializable superclass must run its constructor. Remember, constructors don't run on deserialized classes that implement Serializable.
A, B, D, E, and F are incorrect based on the above. (Objective 3.3)

3. Given:
class TKO {
public static void main(String[] args) {
String s = "-";
Integer x = 343;
long L343 = 343L;
if(x.equals(L343)) s += ".e1 ";
if(x.equals(343)) s += ".e2 ";
Short s1 = (short)((new Short((short)343)) / (new Short((short)49)));
if(s1 == 7) s += "=s ";
if(s1 < new Integer(7+1)) s += "fly ";
System.out.println(s);
} }
Which of the following will be included in the output String s? (Choose all that apply.)
A. .e1
B. .e2
C. =s
D. fly
E. None of the above
F. Compilation fails
G. An exception is thrown at runtime
Answer:
B, C, and D are correct. Remember, that the equals() method for the integer wrappers will only return true if the two primitive types and the two values are equal. With C, it's okay to unbox and use ==. For D, it's okay to create a wrapper object with an expression, and unbox it for comparison with a primitive.
A, E, F, and G are incorrect based on the above. (Remember that A is using the equals() method to try to compare two different types.) (Objective 3.1)

4. Given:
import java.io.*;
class Keyboard { }
public class Computer implements Serializable {
	
		private Keyboard k = new Keyboard();
public static void main(String[] args) {
Computer c = new Computer();
c.storeIt(c);
}
void storeIt(Computer c) {
try {
ObjectOutputStream os = new ObjectOutputStream(
new FileOutputStream("myFile"));
os.writeObject(c);
os.close();
System.out.println("done");
} catch (Exception x) {System.out.println("exc"); }
}
}
What is the result? (Choose all that apply.)
A. exc
B. done
C. Compilation fails
D. Exactly one object is serialized
E. Exactly two objects are serialized
Answer:
A is correct. An instance of type Computer Has-a Keyboard. Because Keyboard doesn't implement Serializable, any attempt to serialize an instance of Computer will cause an exception to be thrown.
B, C, D, and E are incorrect based on the above. If Keyboard did implement Serializable then two objects would have been serialized. (Objective 3.3)

5. Using the fewest fragments possible (and filling the fewest slots possible), complete the code below so that the class builds a directory named "dir3" and creates a file named "file3" inside "dir3". Note you can use each fragment either zero or one times. Code:
import java.io.______________
class Maker {
public static void main(String[] args) {
___________ ___________ ___________
___________ ___________ ___________
___________ ___________ ___________
___________ ___________ ___________
___________ ___________ ___________
___________ ___________ ___________
___________ ___________ ___________
} }
Fragments:
File; FileDescriptor; FileWriter; Directory;
try { .createNewDir(); File dir File
{ } (Exception x) ("dir3"); file
file .createNewFile(); = new File = new File
dir (dir, "file3"); (dir, file); .createFile();
} catch ("dir3", "file3"); .mkdir(); File file

Answer:
import java.io.File;
class Maker {
public static void main(String[] args) {
try {
File dir = new File("dir3");
dir.mkdir();
File file = new File(dir, "file3");
file.createNewFile();
} catch (Exception x) { }
} }

Notes: The new File statements don't make actual files or directories, just objects. You need the mkdir() and createNewFile() methods to actually create the directory and the file. (Objective 3.2)

6. Given that 1119280000000L is roughly the number of milliseconds from Jan. 1, 1970, to June 20, 2005, and that you want to print that date in German, using the LONG style such that "June" will be displayed as "Juni", complete the code using the fragments below. Note: you can use each fragment either zero or one times, and you might not need to fill all of the slots. Code:
import java.___________
import java.___________
class DateTwo {
public static void main(String[] args) {
Date d = new Date(1119280000000L);
DateFormat df = ___________________________
________________ , _________________ );
System.out.println(________________
}
}
Fragments:
io.*; new DateFormat( Locale.LONG
nio.*; DateFormat.getInstance( Locale.GERMANY
util.*; DateFormat.getDateInstance( DateFormat.LONG
text.*; util.regex; DateFormat.GERMANY
date.*; df.format(d)); d.format(df));

Answer:
import java.util.*; import java.text.*; class DateTwo { public static void main(String[] args) { Date d = new Date(1119280000000L); DateFormat df = DateFormat.getDateInstance( DateFormat.LONG, Locale.GERMANY); System.out.println(df.format(d)); } } Notes: Remember that you must build DateFormat objects using static methods. Also remember that you must specify a Locale for a DateFormat object at the time of instantiation. The getInstance() method does not take a Locale. (Objective 3.4)

7. Given:
import java.io.*;
class Directories {
static String [] dirs = {"dir1", "dir2"};
public static void main(String [] args) {
for (String d : dirs) {
// insert code 1 here
File file = new File(path, args[0]);
// insert code 2 here
}
}
}
and that the invocation
java Directories file2.txt
is issued from a directory that has two subdirectories, "dir1" and "dir2", and that "dir1" has a file "file1.txt" and "dir2" has a file "file2.txt", and the output is "false true", which set(s) of code fragments must be inserted? (Choose all that apply.)

A. String path = d; System.out.print(file.exists() + " ");
B. String path = d; System.out.print(file.isFile() + " ");
C. String path = File.separator + d; System.out.print(file.exists() + " ");
D. String path = File.separator + d; System.out.print(file.isFile() + " ");
Answer:
A and B are correct. Because you are invoking the program from the directory whose direct subdirectories are to be searched, you don't start your path with a File.separator character. The exists() method tests for either files or directories; the isFile() method tests only for files. Since we're looking for a file, both methods work.
C and D are incorrect based on the above. (Objective 3.2)

8. Given:
import java.io.*;
public class TestSer {
public static void main(String[] args) {
SpecialSerial s = new SpecialSerial();
try {
ObjectOutputStream os = new ObjectOutputStream(
new FileOutputStream("myFile"));
os.writeObject(s); os.close();
System.out.print(++s.z + " ");
ObjectInputStream is = new ObjectInputStream(
new FileInputStream("myFile"));
SpecialSerial s2 = (SpecialSerial)is.readObject();
is.close();
System.out.println(s2.y + " " + s2.z);
} catch (Exception x) {System.out.println("exc"); }
}
}
class SpecialSerial implements Serializable {
transient int y = 7;
static int z = 9;
}
Which are true? (Choose all that apply.)
A. Compilation fails
B. The output is 10 0 9
C. The output is 10 0 10
D. The output is 10 7 9
E. The output is 10 7 10
F. In order to alter the standard deserialization process you would implement the readObject() method in SpecialSerial
G. In order to alter the standard deserialization process you would implement the defaultReadObject() method in SpecialSerial
Answer:
C and F are correct. C is correct because static and transient variables are not serialized when an object is serialized. F is a valid statement.
A, B, D, and E are incorrect based on the above. G is incorrect because you don't implement the defaultReadObject() method, you call it from within the readObject()method, along with any custom read operations your class needs. (Objective 3.3)

9. Given:
3. public class Theory {
4. public static void main(String[] args) {
5. String s1 = "abc";
6. String s2 = s1;
7. s1 += "d";
8. System.out.println(s1 + " " + s2 + " " + (s1==s2));
9.
10. StringBuffer sb1 = new StringBuffer("abc");
11. StringBuffer sb2 = sb1;
12. sb1.append("d");
13. System.out.println(sb1 + " " + sb2 + " " + (sb1==sb2));
14. }
15. }
Which are true? (Choose all that apply.)
A. Compilation fails
B. The first line of output is abc abc true
C. The first line of output is abc abc false
D. The first line of output is abcd abc false
E. The second line of output is abcd abc false
F. The second line of output is abcd abcd true
G. The second line of output is abcd abcd false
Answer:
D and F are correct. While String objects are immutable, references to Strings are mutable. The code s1 += "d"; creates a new String object. StringBuffer objects are mutable, so the append() is changing the single StringBuffer object to which both StringBuffer references refer.
A, B, C, E, and G are incorrect based on the above. (Objective 3.1)

10. Given:
3. import java.io.*;
4. public class ReadingFor {
5. public static void main(String[] args) {
6. String s;
7. try {
8. FileReader fr = new FileReader("myfile.txt");
9. BufferedReader br = new BufferedReader(fr);
10. while((s = br.readLine()) != null)
11. System.out.println(s);
12. br.flush();
13. } catch (IOException e) { System.out.println("io error"); }
16. }
17. }
And given that myfile.txt contains the following two lines of data:
ab cd
What is the result?
A. ab
B. abcd
C. ab cd
D. a b c d
E. Compilation fails
Answer:
E is correct. You need to call flush() only when you're writing data. Readers don't have flush() methods. If not for the call to flush(), answer C would be correct.
A, B, C, and D are incorrect based on the above. (Objective 3.2)

11. Given:
3. import java.io.*;
4. public class Talker {
5. public static void main(String[] args) {
6. Console c = System.console();
7. String u = c.readLine("%s", "username: ");
8. System.out.println("hello " + u);
9. String pw;
10. if(c != null && (pw = c.readPassword("%s", "password: ")) != null)
11. // check for valid password
12. }
13. }
If line 6 creates a valid Console object, and if the user enters fred as a username and 1234 as a password, what is the result? (Choose all that apply.)
A.
username:
password:
B.
username: fred
password:
C.
username: fred
password: 1234
D. Compilation fails
E. An exception is thrown at runtime
Answer:
D is correct. The readPassword() method returns a char[]. If a char[] were used, answer B would be correct.
A, B, C, and E are incorrect based on the above. (Objective 3.2)

12. Given:
3. import java.io.*;
4. class Vehicle { }
5. class Wheels { }
6. class Car extends Vehicle implements Serializable { }
7. class Ford extends Car { }
8. class Dodge extends Car {
9. Wheels w = new Wheels();
10. }
Instances of which class(es) can be serialized? (Choose all that apply.)
A. Car
B. Ford
C. Dodge
D. Wheels
E. Vehicle
Answer:
A and B are correct. Dodge instances cannot be serialized because they "have" an instance of Wheels, which is not serializable. Vehicle instances cannot be serialized even though the subclass Car can be.
C, D, and E are incorrect based on the above. (Objective 3.3)

13. Given:
3. import java.text.*;
4. public class Slice {
5. public static void main(String[] args) {
6. String s = "987.123456";
7. double d = 987.123456d;
8. NumberFormat nf = NumberFormat.getInstance();
9. nf.setMaximumFractionDigits(5);
10. System.out.println(nf.format(d) + " ");
11. try {
12. System.out.println(nf.parse(s));
13. } catch (Exception e) { System.out.println("got exc"); }
14. }
15. }
Which are true? (Choose all that apply.)
A. The output is 987.12345 987.12345
B. The output is 987.12346 987.12345
C. The output is 987.12345 987.123456
D. The output is 987.12346 987.123456
E. The try/catch block is unnecessary
F. The code compiles and runs without exception
G. The invocation of parse() must be placed within a try/catch block
Answer:
D, F, and G are correct. The setMaximumFractionDigits() applies to the formatting but not the parsing. The try/catch block is placed appropriately. This one might scare you into thinking that you'll need to memorize more than you really do. If you can remember that you're formatting the number and parsing the string you should be fine for the exam.
A, B, C, and E are incorrect based on the above. (Objective 3.4)

14. Given:
3. import java.util.regex.*;
4. public class Archie {
5. public static void main(String[] args) {
6. Pattern p = Pattern.compile(args[0]);
7. Matcher m = p.matcher(args[1]);
8. int count = 0;
9. while(m.find())
10. count++;
11. System.out.print(count);
12. }
13. }
And given the command line invocation:
java Archie "\d+" ab2c4d67
What is the result?
A. 0
B. 3
C. 4
D. 8
E. 9
F. Compilation fails
Answer:
B is correct. The "\d" metacharacter looks for digits, and the + quantifier says look for "one or more" occurrences. The find() method will find three sets of one or more consecutive digits: 2, 4, and 67.
A, C, D, E, and F are incorrect based on the above. (Objective 3.5)

15. Given:
import java.util.*;
public class Looking {
public static void main(String[] args) {
String input = "1 2 a 3 45 6";
Scanner sc = new Scanner(input);
int x = 0;
do {
x = sc.nextInt();
System.out.print(x + " ");
} while (x!=0);
}
}
What is the result?
A. 1 2
B. 1 2 3 45 6
C. 1 2 3 4 5 6
D. 1 2 a 3 45 6
E. Compilation fails
F. 1 2 followed by an exception
Answer:
F is correct. The nextXxx() methods are typically invoked after a call to a hasNextXxx(), which determines whether the next token is of the correct type.
A, B, C, D, and E are incorrect based on the above. (Objective 3.5)


.


regards,
TechDexters Support Team
Hyderabad.


for Feedback and Support simply drop a mail in
techdexters{at}gmail.com
Remember to replace the {at} with @ in the email addresses

Aug 13, 2012

String Handling



Using String, StringBuffer, and StringBuilder (Objective 3.1)
  1. String objects are immutable, and String reference variables are not.
  2. If you create a new String without assigning it, it will be lost to your program.
  3. If you redirect a String reference to a new String, the old String can be lost.
  4. String methods use zero-based indexes, except for the second argument of substring().
  5. The String class is final¡Âªits methods can't be overridden.
  6. When the JVM finds a String literal, it is added to the String literal pool.
  7. Strings have a method: length(); arrays have an attribute named length.
  8. The StringBuffer's API is the same as the new StringBuilder's API, except that StringBuilder's methods are not synchronized for thread safety.
  9. StringBuilder methods should run faster than StringBuffer methods.
  10. All of the following bullets apply to both StringBuffer and StringBuilder:
    1. They are mutable - they can change without creating a new object.
    2. StringBuffer methods act on the invoking object, and objects can change without an explicit assignment in the statement.
    3. StringBuffer equals() is not overridden; it doesn't compare values.
  11. Remember that chained methods are evaluated from left to right.
  12. String methods to remember: charAt(), concat(), equalsIgnoreCase(), length(), replace(), substring(), toLowerCase(), toString(), toUpperCase(), and trim().
  13. StringBuffer methods to remember: append(), delete(), insert(), reverse(), and toString().


File I/O (Objective 3.2)
  1. The classes you need to understand in java.io are File, FileReader, BufferedReader, FileWriter, BufferedWriter, PrintWriter, and Console.
  2. A new File object doesn't mean there's a new file on your hard drive.
  3. File objects can represent either a file or a directory.
  4. The File class lets you manage (add, rename, and delete) files and directories.
  5. The methods createNewFile() and mkdir() add entries to your file system.
  6. FileWriter and FileReader are low-level I/O classesYou can use them to write and read files, but they should usually be wrapped.
  7. Classes in java.io are designed to be "chained" or "wrapped." (This is a common use of the decorator design pattern.)
  8. It's very common to "wrap" a BufferedReader around a FileReader or a BufferedWriter around a FileWriter, to get access to higher-level (more convenient) methods.
  9. PrintWriters can be used to wrap other Writers, but as of Java 5 they can be built directly from Files or Strings.
  10. Java 5 PrintWriters have new append(), format(), and printf() methods.
  11. Console objects can read non-echoed input and are instantiated using System.console().


Serialization (Objective 3.3)
  1. The classes you need to understand are all in thejava.io package; they include: ObjectOutputStream and ObjectInputStream primarily, and FileOutputStream and FileInputStream because you will use them to create the low-level streams that the ObjectXxxStream classes will use.
  2. A class must implement Serializable before its objects can be serialized.
  3. The ObjectOutputStream.writeObject() method serializes objects, and the ObjectInputStream.readObject() method deserializes objects.
  4. If you mark an instance variable transient, it will not be serialized even thought the rest of the object's state will be.
  5. You can supplement a class's automatic serialization process by implementing the writeObject() and readObject() methodsIf you do this, embedding calls to defaultWriteObject() and defaultReadObject(),respectively, will handle the part of serialization that happens normally.
  6. If a superclass implements Serializable, then its subclasses do automatically.
  7. If a superclass doesn't implement Serializable, then when a subclass object is deserialized, the superclass constructor will be invoked, along with its superconstructor(s).
  8. DataInputStream and DataOutputStream aren't actually on the exam, inspite of what the Sun objectives say.


Dates, Numbers, and Currency (Objective 3.4)
  1. The classes you need to understand are java.util.Date, java.util.Calendar, java.text.DateFormat, java.text.NumberFormat, and java.util.Locale.
  2. Most of the Date class's methods have been deprecated.
  3. A Date is stored as a long, the number of milliseconds since January 1, 1970.
  4. Date objects are go-betweens the Calendar and Locale classes.
  5. The Calendar provides a powerful set of methods to manipulate dates, performing tasks such as getting days of the week, or adding some number of months or years (or other increments) to a date.
  6. Create Calendar instances using static factory methods (getInstance()).
  7. The Calendar methods you should understand are add(), which allows you to add or subtract various pieces (minutes, days, years, and so on)  of dates, and roll(), which works like add() but doesn't increment a date's bigger pieces(For example: adding 10 months to an October date changes the month to August, but doesn't increment the Calendar's year value.)
  8. DateFormat instances are created using static factory methods (getInstance() and getDateInstance()).
  9. There are several format "styles" available in the DateFormat class.
  10. DateFormat styles can be applied against various Locales to create a wide array of outputs for any given date.
  11. The DateFormat.format() method is used to create Strings containing properly formatted dates.
  12. The Locale class is used in conjunction with DateFormat and NumberFormat.
  13. Both DateFormat and NumberFormat objects can be constructed with a specific, immutable Locale.
  14. For the exam you should understand creating Locales using language, or a combination of language and country.

Parsing, Tokenizing, and Formatting (Objective 3.5)
  1. regex is short for regular expressions, which are the patterns used to search for data within large data sources.
  2. regex is a sub-language that exists in Java and other languages (such as Perl).
  3. regex lets you to create search patterns using literal characters or metacharactersMetacharacters allow you to search for slightly more abstract data like "digits" or "whitespace".
  4. Study the \d, \s, \w, and metacharacters
  5. regex provides for quantifiers which allow you to specify concepts like: "look for one or more digits in a row."
  6. Study the ?, *, and + greedy quantifiers.
  7. Remember that metacharacters and Strings don't mix well unless you remember to "escape" them properlyFor instance String s = "\\d";
  8. The Pattern and Matcher classes have Java's most powerful regex capabilities.
  9. You should understand the Pattern compile() method and the Matcher matches(), pattern(), find(), start(), and group() methods.
  10. You WON'T need to understand Matcher's replacement-oriented methods.
  11. You can use java.util.Scanner to do simple regex searches, but it is primarily intended for tokenizing.
  12. Tokenizing is the process of splitting delimited data into small pieces.
  13. In tokenizing, the data you want is called tokens, and the strings that separate the tokens are called delimiters.
  14. Tokenizing can be done with the Scanner class, or with String.split().
  15. Delimiters are single characters like commas, or complex regex expressions.
  16. The Scanner class allows you to tokenize data from within a loop, which allows you to stop whenever you want to.
  17. The Scanner class allows you to tokenize Strings or streams or files.
  18. The String.split() method tokenizes the entire source data all at once, so large amounts of data can be quite slow to process.
  19. New to Java 5 are two methods used to format data for output. These methods are format() and printf()These methods are found in the PrintStream class, an instance of which is the out in System.out.
  20. The format() and printf() methods have identical functionality.
  21. Formatting data with printf() (or format()) is accomplished using formatting strings that are associated with primitive or string arguments.
  22. The format() method allows you to mix literals in with your format strings.
  23. The format string values you should know are
    1. Flags: -, +, 0, "," , and (
    2. Conversions: b, c, d, f, and s
  24. If your conversion character doesn't match your argument type, an exception will be thrown.

regards,
TechDexters Support Team
Hyderabad.


for Feedback and Support simply drop a mail in
techdexters{at}gmail.com
Remember to replace the {at} with @ in the email addresses

Aug 11, 2012

Exercise - 5 (Exceptions, Assertions)



1.Given
class One {
	public static void main(String[] args) {
		int assert = 0;
	}
}
class Two {
	public static void main(String[] args) {
		assert(false);
	}
}
And the four command-line invocations:
javac -source 1.3 One.java
javac -source 1.4 One.java
javac -source 1.3 Two.java
javac -source 1.4 Two.java
What is the result? (Choose all that apply.)
A. Only one compilation will succeed
B. Exactly two compilations will succeed
C. Exactly three compilations will succeed
D. All four compilations will succeed
E. No compiler warnings will be produced
F. At least one compiler warning will be produced
Answer:
B and F are correct. Class One will compile (and issue a warning) using the 1.3 flag, and class Two will compile using the 1.4 flag.
A, C, D, and E are incorrect based on the above. (Objective 2.3)

2.Given
class Plane {
	static String s = "-";
	public static void main(String[] args) {
		new Plane().s1();
		System.out.println(s);
	}
	void s1() {
		try { s2(); }
		catch (Exception e) { s += "c"; }
	}
	void s2() throws Exception {
		s3(); s += "2";
		s3(); s += "2b";
	}
	void s3() throws Exception {
		throw new Exception();
	} 
}
What is the result?
A. -
B. -c
C. -c2
D. -2c
E. -c22b
F. -2c2b
G. -2c2bc
H. Compilation fails
Answer:
B is correct. Once s3() throws the exception to s2(), s2() throws it to s1(), and no more of s2()'s code will be executed.
A, C, D, E, F, G, and H are incorrect based on the above. (Objective 2.5)

3.Given
try { int x = Integer.parseInt("two"); }
Which could be used to create an appropriate catch block? (Choose all that apply.)
A. ClassCastException
B. IllegalStateException
C. NumberFormatException
D. IllegalArgumentException
E. ExceptionInInitializerError
F. ArrayIndexOutOfBoundsException
Answer:
C and D are correct. Integer.parseInt can throw a NumberFormatException, and IllegalArgumentException is its superclass (i.e., a broader exception).
A, B, E, and F are not in NumberFormatException's class hierarchy. (Objective 2.6)

4. Which are true? (Choose all that apply.)
A. It is appropriate to use assertions to validate arguments to methods marked public
B. It is appropriate to catch and handle assertion errors
C. It is NOT appropriate to use assertions to validate command-line arguments
D. It is appropriate to use assertions to generate alerts when you reach code that should not be reachable
E. It is NOT appropriate for assertions to change a program's state
Answer:
C, D, and E are correct statements.
A is incorrect. It is acceptable to use assertions to test the arguments of private methods. B is incorrect. While assertion errors can be caught, Sun discourages you from doing so. (Objective 2.3)

5.Given
class Loopy {
	public static void main(String[] args) {
		int[] x = {7,6,5,4,3,2,1};
		// insert code here
		System.out.print(y + " ");
		}
	} 
}
Which, inserted independently at line 4, compiles? (Choose all that apply.)
A. for(int y : x) {
B. for(x : int y) {
C. int y = 0; for(y : x) {
D. for(int y=0, z=0; z < x.length; z++) { y = x[z];
E. for(int y=0, int z=0; z < x.length; z++) { y = x[z];
F. int y = 0; for(int z=0; z<x.length; z++) { y = x[z];
Answer:
A, D, and F are correct. A is an example of the enhanced for loop. D and F are examples of the basic for loop.
B is incorrect because its operands are swapped. C is incorrect because the enhanced for must declare its first operand. E is incorrect syntax to declare two variables in a for statement. (Objective 2.2)

6.Given
class Emu {
	static String s = "-";
	public static void main(String[] args) {
		try {
			throw new Exception();
		} catch (Exception e) {
			try {
				try { throw new Exception();
				} catch (Exception ex) { s += "ic "; }
				throw new Exception(); 
			}
			catch (Exception x) { s += "mc "; }
			finally { s += "mf "; }
		} finally { s += "of "; }
		System.out.println(s);
	} 
}
What is the result?
A. -ic of
B. -mf of
C. -mc mf
D. -ic mf of
E. -ic mc mf of
F. -ic mc of mf
G. Compilation fails
Answer:
E is correct. There is no problem nesting try / catch blocks. As is normal, when an exception is thrown, the code in the catch block runs, then the code in the finally block runs.
A, B, C, D, and F are incorrect based on the above. (Objective 2.5)

7.Given
class SubException extends Exception { }
class SubSubException extends SubException { }

public class CC { void doStuff() throws SubException { } }

class CC2 extends CC { void doStuff() throws SubSubException { } }

class CC3 extends CC { void doStuff() throws Exception { } }

class CC4 extends CC { void doStuff(int x) throws Exception { } }

class CC5 extends CC { void doStuff() { } }
What is the result? (Choose all that apply.)
A. Compilation succeeds
B. Compilation fails due to an error on line 6
C. Compilation fails due to an error on line 8
D. Compilation fails due to an error on line 10
E. Compilation fails due to an error on line 12
Answer:
C is correct. An overriding method cannot throw a broader exception than the method it's overriding. Class CC4's method is an overload, not an override.
A, B, D, and E are incorrect based on the above. (Objectives 1.5, 2.4)

8.Given
public class Ebb {
	static int x = 7;
	public static void main(String[] args) {
		String s = "";
		for(int y = 0; y < 3; y++) {
			x++;
			switch(x) {
				case 8: s += "8 ";
				case 9: s += "9 ";
				case 10: { s+= "10 "; break; }
				default: s += "d ";
				case 13: s+= "13 ";
			}
		}
		System.out.println(s);
	}
	static { x++; }
}
What is the result?
A. 9 10 d
B. 8 9 10 d
C. 9 10 10 d
D. 9 10 10 d 13
E. 8 9 10 10 d 13
F. 8 9 10 9 10 10 d 13
G. Compilation fails
Answer:
D is correct. Did you catch the static initializer block? Remember that switches work on "fall-thru" logic, and that fall-thru logic also applies to the default case, which is used when no other case matches.
A, B, C, E, F, and G are incorrect based on the above. (Objective 2.1)

9.Given
class Infinity { }
public class Beyond extends Infinity {
static Integer i;
public static void main(String[] args) {
int sw = (int)(Math.random() * 3);
switch(sw) {
case 0: { for(int x = 10; x > 5; x++)
if(x > 10000000) x = 10;
break; }
case 1: { int y = 7 * i; break; }
case 2: { Infinity inf = new Beyond();
Beyond b = (Beyond)inf; }
}
}
}
And given that line 7 will assign the value 0, 1, or 2 to sw, which are true? (Choose all that apply.)
A. Compilation fails
B. A ClassCastException might be thrown
C. A StackOverflowError might be thrown
D. A NullPointerException might be thrown
E. An IllegalStateException might be thrown
F. The program might hang without ever completing
G. The program will always complete without exception
Answer:
D and F are correct. Because i was not initialized, case 1 will throw an NPE. Case 0 will initiate an endless loop, not a stack overflow. Case 2's downcast will not cause an exception.
A, B, C, E, and G are incorrect based on the above. (Objective 2.6)

10.Given
public class Circles {
	public static void main(String[] args) {
		int[] ia = {1,3,5,7,9};
		for(int x : ia) {
			for(int j = 0; j < 3; j++) {
				if(x > 4 && x < 8) continue;
				System.out.print(" " + x);
				if(j == 1) break;
					continue;
			}
			continue;
		}
	}
}
What is the result?
A. 1 3 9
B. 5 5 7 7
C. 1 3 3 9 9
D. 1 1 3 3 9 9
E. 1 1 1 3 3 3 9 9 9
F. Compilation fails
Answer:
D is correct. The basic rule for unlabeled continue statements is that the current iteration stops early and execution jumps to the next iteration. The last two continue statements are redundant!
A, B, C, E, and F are incorrect based on the above. (Objective 2.2)

11.Given
public class OverAndOver {
	static String s = "";
	public static void main(String[] args) {
		try {
			s += "1";
			throw new Exception();
		} catch (Exception e) { s += "2";
		} finally { s += "3"; doStuff(); s += "4";
		}
		System.out.println(s);
	}
	static void doStuff() { int x = 0; int y = 7/x; }
}
What is the result?
A. 12
B. 13
C. 123
D. 1234
E. Compilation fails
F. 123 followed by an exception
G. 1234 followed by an exception
H. An exception is thrown with no other output
Answer:
H is correct. It's true that the value of String s is 123 at the time that the divide-byzero exception is thrown, but finally() is not guaranteed to complete, and in this case finally() never completes, so the System.out.println (S.O.P.) never executes.
A, B, C, D, E, F, and G are incorrect based on the above. (Objective 2.5)

12.Given
public class Wind {
	public static void main(String[] args) {
	foreach:
		for(int j=0; j<5; j++) {
			for(int k=0; k< 3; k++) {
				System.out.print(" " + j);
				if(j==3 && k==1) break foreach;
				if(j==0 || j==2) break;
			}
		}
	}
}
What is the result?
A. 0 1 2 3
B. 1 1 1 3 3
C. 0 1 1 1 2 3 3
D. 1 1 1 3 3 4 4 4
E. 0 1 1 1 2 3 3 4 4 4
F. Compilation fails
Answer:
C is correct. A break breaks out of the current innermost loop and continues. A labeled break breaks out of and terminates the current loops.
A, B, D, E, and F are incorrect based on the above. (Objective 2.2)

13.Given
public class Gotcha {
public static void main(String[] args) {
// insert code here

}
void go() {
go();
}
}
And given the following three code fragments:
I. new Gotcha().go();
II. try { new Gotcha().go(); }
    catch (Error e) { System.out.println("ouch"); }
III. try { new Gotcha().go(); }
catch (Exception e) { System.out.println("ouch"); }
When fragments I - III are added, independently, at line 3, which are true? (Choose all that apply.)
A. Some will not compile
B. They will all compile
C. All will complete normally
D. None will complete normally
E. Only one will complete normally
F. Two of them will complete normally
Answer:
B and E are correct. First off, go() is a badly designed recursive method, guaranteed to cause a StackOverflowError. Since Exception is not a superclass of Error, catching an Exception will not help handle an Error, so fragment III will not complete normally. Only fragment II will catch the Error.
A, C, D, and F are incorrect based on the above. (Objective 2.5)

14.Given
public class Clumsy {
	public static void main(String[] args) {
		int j = 7;
		assert(++j > 7);
		assert(++j > 8): "hi";
		assert(j > 10): j=12;
		assert(j==12): doStuff();
		assert(j==12): new Clumsy();
	}
	static void doStuff() { }
}
Which are true? (Choose all that apply.)
A. Compilation succeeds
B. Compilation fails due to an error on line 4
C. Compilation fails due to an error on line 5
D. Compilation fails due to an error on line 6
E. Compilation fails due to an error on line 7
F. Compilation fails due to an error on line 8
Answer:
E is correct. When an assert statement has two expressions, the second expression must return a value. The only two-expression assert statement that doesn't return a value is on line 7.
A, B, C, D, and F are incorrect based on the above. (Objective 2.3)

15.Given
public class Frisbee {
	// insert code here
	int x = 0;
	System.out.println(7/x);
	}
}
And given the following four code fragments:
I. public static void main(String[] args) {
II. public static void main(String[] args) throws Exception {
III. public static void main(String[] args) throws IOException {
IV. public static void main(String[] args) throws RuntimeException {
If the four fragments are inserted independently at line 2, which are true? (Choose all that apply.)
A. All four will compile and execute without exception
B. All four will compile and execute and throw an exception
C. Some, but not all, will compile and execute without exception
D. Some, but not all, will compile and execute and throw an exception
E. When considering fragments II, III, and IV, of those that will compile, adding a try/catch block around line 4 will cause compilation to fail
Answer:
D is correct. This is kind of sneaky, but remember that we're trying to toughen you up for the real exam. If you're going to throw an IOException, you have to import the java.io package or declare the exception with a fully qualified name.
E is incorrect because it's okay to both handle and declare an exception. A, B, and C are incorrect based on the above. (Objective 2.4)

16.Given
class MyException extends Exception { }
class Tire {
	void doStuff() { }
}
public class Retread extends Tire {
	public static void main(String[] args) {
	new Retread().doStuff();
}
	// insert code here
		System.out.println(7/0);
	}
}
And given the following four code fragments:
I. void doStuff() {
II. void doStuff() throws MyException {
III. void doStuff() throws RuntimeException {
IV. void doStuff() throws ArithmeticException {
When fragments I - IV are added, independently, at line 10, which are true? (Choose all that apply.)
A. None will compile
B. They will all compile
C. Some, but not all, will compile
D. All of those that compile will throw an exception at runtime
E. None of those that compile will throw an exception at runtime
F. Only some of those that compile will throw an exception at runtime
Answer:
C and D are correct. An overriding method cannot throw checked exceptions that are broader than those thrown by the overridden method. However an overriding method can throw RuntimeExceptions not thrown by the overridden method.
A, B, E, and F are incorrect based on the above. (Objective 2.4)




regards,
TechDexters Support Team
Hyderabad.


for Feedback and Support simply drop a mail in
techdexters{at}gmail.com
Remember to replace the {at} with @ in the email addresses
e

Aug 8, 2012

Exceptions, Assertions


Writing Code Using if and switch Statements (Obj. 2.1)
  • The only legal expression in an if statement is a boolean expression, in other words an expression that resolves to a boolean or a Boolean variable. 
  • Watch out for boolean assignments (=) that can be mistaken for boolean equality (==) tests:
           boolean x = false;
           if (x = true) { } // an assignment, so x will always be true!
  • Curly braces are optional for if blocks that have only one conditional statement. But watch out for misleading indentations.
  • switch statements can evaluate only to enums or the byte, short, int, and char data types. You can't say,
               long s = 30;
               switch(s) { }
  • The case constant must be a literal or final variable, or a constant expression, including an enum. You cannot have a case that includes a nonfinal variable, or a range of values.
  • If the condition in a switch statement matches a case constant, execution will run through all code in the switch following the matching case statement until a break statement or the end of the switch statement is encountered. In other words, the matching case is just the entry point into the case block, but unless there's a break statement, the matching case is not the only case code that runs.
  • The default keyword should be used in a switch statement if you want to run some code when none of the case values match the conditional value.
  • The default block can be located anywhere in the switch block, so if no case matches, the default block will be entered, and if the default does not contain a break, then code will continue to execute (fall-through) to the end of the switch or until the break statement is encountered.

Writing Code Using Loops (Objective 2.2)
  • A basic for statement has three parts: declaration and/or initialization, boolean evaluation, and the iteration expression.
  • If a variable is incremented or evaluated within a basic for loop, it must be declared before the loop, or within the for loop declaration.
  • A variable declared (not just initialized) within the basic for loop declaration cannot be accessed outside the for loop (in other words, code below the for loop won't be able to use the variable).
  • You can initialize more than one variable of the same type in the first part of the basic for loop declaration; each initialization must be separated by a comma.
  • An enhanced for statement (new as of Java 6), has two parts, the declaration and the expression. It is used only to loop through arrays or collections.
  • With an enhanced for, the expression is the array or collection through which you want to loop.
  • With an enhanced for, the declaration is the block variable, whose type is compatible with the elements of the array or collection, and that variable contains the value of the element for the given iteration.
  • You cannot use a number (old C-style language construct) or anything that does not evaluate to a boolean value as a condition for an if statement or looping construct. You can't, for example, say if(x), unless x is a boolean variable.
  • The do loop will enter the body of the loop at least once, even if the test condition is not met.

Using break and continue (Objective 2.2)
  • An unlabeled break statement will cause the current iteration of the innermost looping construct to stop and the line of code following the loop to run.
  • An unlabeled continue statement will cause: the current iteration of the innermost loop to stop, the condition of that loop to be checked, and if the condition is met, the loop to run again.
  • If the break statement or the continue statement is labeled, it will cause similar action to occur on the labeled loop, not the innermost loop.

Handling Exceptions (Objectives 2.4, 2.5, and 2.6)
  • Exceptions come in two flavors: checked and unchecked.
  • Checked exceptions include all subtypes of Exception, excluding classes that extend RuntimeException.
  • Checked exceptions are subject to the handle or declare rule; any method that might throw a checked exception (including methods that invoke methods that can throw a checked exception) must either declare the exception using throws, or handle the exception with an appropriate try/catch.
  • Subtypes of Error or RuntimeException are unchecked, so the compiler doesn't enforce the handle or declare rule. You're free to handle them, or to declare them, but the compiler doesn't care one way or the other. 
  • If you use an optional finally block, it will always be invoked, regardless of whether an exception in the corresponding try is thrown or not, and regardless of whether a thrown exception is caught or not.
  • The only exception to the finally-will-always-be-called rule is that a finally will not be invoked if the JVM shuts down. That could happen if code from the try or catch blocks calls System.exit().
  • Just because finally is invoked does not mean it will complete. Code in the finally block could itself raise an exception or issue a System.exit().
  • Uncaught exceptions propagate back through the call stack, starting from the method where the exception is thrown and ending with either the first method that has a corresponding catch for that exception type or a JVM shutdown (which happens if the exception gets to main(), and main() is "ducking" the exception by declaring it).
  • You can create your own exceptions, normally by extending Exception or one of its subtypes. Your exception will then be considered a checked exception,and the compiler will enforce the handle or declare rule for that exception.
  • All catch blocks must be ordered from most specific to most general. If you have a catch clause for both IOException and Exception, you must put the catch for IOException first in your code. Otherwise, the IOException would be caught by catch(Exception e), because a catch argument can catch the specified exception or any of its subtypes! The compiler will stop you from defining catch clauses that can never be reached. 
  • Some exceptions are created by programmers, some by the JVM.

Working with the Assertion Mechanism (Objective 2.3)
  • Assertions give you a way to test your assumptions during development and debugging.
  • Assertions are typically enabled during testing but disabled during deployment.
  • You can use assert as a keyword (as of version 1.4) or an identifier, but not both together. To compile older code that uses assert as an identifier (for example, a method name), use the -source 1.3 command-line flag to javac.
  • Assertions are disabled at runtime by default. To enable them, use a command- line flag -ea or -enableassertions.
  • Selectively disable assertions by using the -da or -disableassertions flag. 
  • If you enable or disable assertions using the flag without any arguments, you're enabling or disabling assertions in general. You can combine enabling and disabling switches to have assertions enabled for some classes and/or packages, but not others. 
  • You can enable and disable assertions on a class-by-class basis, using the following syntax:
java -ea -da:MyClass TestClass
  • You can enable and disable assertions on a package-by-package basis, and any package you specify also includes any subpackages (packages further down the directory hierarchy).
  • Do not use assertions to validate arguments to public methods.
  • Do not use assert expressions that cause side effects. Assertions aren't guaranteed to always run, and you don't want behavior that changes depending on whether assertions are enabled.
  • Do use assertions—even in public methods—to validate that a particular code block will never be reached. You can use assert false; for code that should never be reached, so that an assertion error is thrown immediately if the assert statement is executed.



regards,
TechDexters Support Team
Hyderabad.


for Feedback and Support simply drop a mail in
techdexters{at}gmail.com
Remember to replace the {at} with @ in the email addresses