Appendix F Mock Exam

This is a mock exam for Sun Certified Programmer for the Java Platform Standard Edition 6 (SCJP 1.6). It comprises brand new questions, which are similar to the questions that can be expected on the real exam. Working through this exam will give the reader a good indication of how well she is prepared for the real exam, and whether any topics need further study.

Questions

Q1 Given the following class, which statements can be inserted at (1) without causing a compilation error?

   public class Q6db8 {
     int a;
     int b = 0;
     static int c;

     public void m() {
       int d;
       int e = 0;

       // (1) INSERT CODE HERE.
     }
   }

Select the four correct answers.

(a) a++;

(b) b++;

(c) c++;

(d) d++;

(e) e++;

Q2 What is wrong with the following code?

   class MyException extends Exception {}

   public class Qb4ab {
     public void foo() {
       try {

         bar();
       } finally {
         baz();
       } catch (MyException e) {}
     }

     public void bar() throws MyException {
       throw new MyException();
     }

     public void baz() throws RuntimeException {
       throw new RuntimeException();
     }
   }

Select the one correct answer.

(a) Since the method foo() does not catch the exception generated by the method baz(), it must declare the RuntimeException in a throws clause.

(b) A try block cannot be followed by both a catch and a finally block.

(c) An empty catch block is not allowed.

(d) A catch block cannot follow a finally block.

(e) A finally block must always follow one or more catch blocks.

Q3 What will be written to the standard output when the following program is run?

   public class Qd803 {
     public static void main(String[] args) {
       String word = "restructure";
       System.out.println(word.substring(2, 3));
     }
   }

Select the one correct answer.

(a) est

(b) es

(c) str

(d) st

(e) s

Q4 Given that a static method doIt() in the class Work represents work to be done, which block of code will succeed in starting a new thread that will do the work?

Select the one correct answer.

(a) Runnable r = new Runnable() {
  public void run() {
    Work.doIt();
  }
};
Thread t = new Thread(r);
t.start();

(b) Thread t = new Thread() {
  public void start() {
    Work.doIt();
  }
};
t.start();

(c) Runnable r = new Runnable() {
  public void run() {
    Work.doIt();
  }
};
r.start();

(d) Thread t = new Thread(new Work());
t.start();

(e) Runnable t = new Runnable() {
  public void run() {
    Work.doIt();
  }
};
t.run();

Q5 Which import statements, when inserted at (4) in package p3, will result in a program that can be compiled and run?

package p2;
enum March {LEFT, RIGHT;                          // (1)
  public String toString() {
    return "Top-level enum";
  }
}
public class DefenceInDepth {
  public enum March {LEFT, RIGHT;                 // (2)
    public String toString() {
      return "Static enum";
    }
  }
  public enum Military { INFANTRY, AIRFORCE;
    public static enum March {LEFT, RIGHT;        // (3)
      public String toString() {
        return "Statically nested enum";
      }
    }
  }
}
____________________________________________________
package p3;
// (4) INSERT IMPORTS HERE
public class MarchingOrders {
  public static void main(String[] args) {
    System.out.println(March.LEFT);
    System.out.println(DefenceInDepth.March.LEFT);
    System.out.println(p2.DefenceInDepth.March.LEFT);
    System.out.println(Military.March.LEFT);
    System.out.println(DefenceInDepth.Military.March.LEFT);
    System.out.println(p2.DefenceInDepth.Military.March.LEFT);
    System.out.println(LEFT);
  }
}

Select the three correct answers.

(a) import p2.*;
import p2.DefenceInDepth.*;
import static p2.DefenceInDepth.Military.March.LEFT;
(b) import p2.*;
import static p2.DefenceInDepth.*;
import static p2.DefenceInDepth.Military.March.LEFT;
(c) import p2.DefenceInDepth;
import static p2.DefenceInDepth.*;
import static p2.DefenceInDepth.Military.March.LEFT;
(d) import static p2.DefenceInDepth;
import static p2.DefenceInDepth.*;
import static p2.DefenceInDepth.Military.March.LEFT;
(e) import p2.*;
import static p2.DefenceInDepth.*;
import static p2.DefenceInDepth.Military.*;
(f) import p2.*;
import static p2.DefenceInDepth.*;
import static p2.DefenceInDepth.Military.March;

Q6 What will be printed when the following program is run?

   public class Q8929 {
     public static void main(String[] args) {
       for (int i = 12; i > 0; i -= 3)
         System.out.print(i);
       System.out.println("");
     }
   }

Select the one correct answer.

(a) 12

(b) 129630

(c) 12963

(d) 36912

(e) None of the above.

Q7 What will be the result of compiling and running the following program?

   public class Q275d {
     static   int a;
     int b;

     public Q275d() {
       int c;
       c = a;
       a++;
       b += c;
     }

     public static void main(String[] args) {
       new Q275d();
     }
   }

Select the one correct answer.

(a) The code will fail to compile, since the constructor is trying to access the static members.

(b) The code will fail to compile, since the constructor is trying to use the static field a before it has been initialized.

(c) The code will fail to compile, since the constructor is trying to use the field b before it has been initialized.

(d) The code will fail to compile, since the constructor is trying to use the local variable c before it has been initialized.

(e) The code will compile and run without any problems.

Q8 Which statement is true about the compilation and execution of the following program with assertions enabled?

   public class Qf1e3 {
     String s1;
     String s2 = "hello";
     String s3;

     Qf1e3() {
       s1 = "hello";
     }

     public static void main(String[] args) {
       (new Qf1e3()).f();
     }

     {
       s3 = "hello";
     }

     void f() {
       String s4 = "hello";
       String s5 = new String("hello");
       assert(s1.equals(s2)); // (1)
       assert(s2.equals(s3)); // (2)
       assert(s3 == s4);      // (3)
       assert(s4 == s5);      // (4)
     }
   }

Select the one correct answer.

(a) The compilation will fail.

(b) The assertion on the line marked (1) will fail.

(c) The assertion on the line marked (2) will fail.

(d) The assertion on the line marked (3) will fail.

(e) The assertion on the line marked (4) will fail.

(f) The program will run without any errors.

Q9 Under which circumstance will a thread stop?

Select the one correct answer.

(a) The run() method that the thread is executing ends.

(b) When the call to the start() method of the Thread object returns.

(c) The suspend() method is called on the Thread object.

(d) The wait() method is called on the Thread object.

Q10 Which statements are true about the following program?

public class Q100_82 {
  public static void main(String[] args) {
    Object o = choose(991, "800");                                 // (1)
    Number n1 = choose(991, 3.14);                                 // (2)
    Number n2 = Q100_82.<Double>choose((double)991, 3.14);         // (3)
    int k = (int) choose(1.3, 3.14);                               // (4)
    int l = (int) (double) choose(1.3, 3.14);                      // (5)
  }

  public static <T extends Comparable<T>> T choose(T t1, T t2) {
    return t1.compareTo(t2) >= 0 ? t1 : t2;
  }
}

Select the two correct answers.

(a) The class must be declared as a generic type:

public class Q100_82<T extends Comparable<T>> { ... }

(b) The compiler reports errors in (1).

(c) The compiler reports no errors in (2).

(d) The compiler reports no errors in (3).

(e) The compiler reports no errors in (4).

(f) The compiler reports errors in (5).

Q11 What will be written to the standard output when the following program is run?

   class Base {
     int i;
     Base() { add(1); }
     void add(int v) { i += v; }
     void print() { System.out.println(i); }
   }

   class Extension extends Base {
     Extension() { add(2); }
     void add(int v) { i += v*2; }
   }

   public class Qd073 {
     public static void main(String[] args) {
       bogo(new Extension());
     }

     static void bogo(Base b) {
       b.add(8);
       b.print();
     }
   }

Select the one correct answer.

(a) 9

(b) 18

(c) 20

(d) 21

(e) 22

Q12 Which collection implementation is suitable for maintaining an ordered sequence of objects, when objects are frequently inserted in and removed from the middle of the sequence?

Select the one correct answer.

(a) TreeMap

(b) HashSet

(c) Vector

(d) LinkedList

(e) ArrayList

Q13 Which statements, when inserted at (1), will make the program print 1 on the standard output when executed?

   public class Q4a39 {
     int a = 1;
     int b = 1;
     int c = 1;

     class Inner {
       int a = 2;

       int get() {
         int c = 3;
         // (1) INSERT CODE HERE.
         return c;
       }
     }

     Q4a39() {
       Inner i = new Inner();
       System.out.println(i.get());
     }

     public static void main(String[] args) {
       new Q4a39();
     }
   }

Select the two correct answers.

(a) c = b;

(b) c = this.a;

(c) c = this.b;

(d) c = Q4a39.this.a;

(e) c = c;

Q14 Given the following code:

   import java.io.*;
   public class Q800_110 {

     public static void main(String[] args)
     throws IOException, ClassNotFoundException {
       String[] dirNames = {
            "." + File.separator + "dir1",
           "." + File.separator + "dir2",
           "." + File.separator + "dir1" + File.separator + "dir2"
       };
       for(String dir : dirNames) {
         File file = new File(dir, "myFile.txt");
         System.out.print(/* INSERT EXPRESSION HERE */);   // (1)
       }
     }
   }

Assume that each directory named in the array dirNames has a file named "myFile.txt".

Which expressions, when inserted at (1), will result in the output "truetruetrue"?

Select the three correct answers.

(a) file.found()

(b) file.isFile()

(c) !file.isDirectory()

(d) file.exists()

(e) file.isAFile()

(f) !file.isADirectory()

Q15 Which is the first line in the following code after which the object created in the line marked (0) will be a candidate for garbage collection, assuming no compiler optimizations are done?

   public class Q76a9 {
     static String f() {
       String a = "hello";
       String b = "bye";            // (0)
       String c = b + "!";          // (1)
       String d = b;                // (2)

       b = a;                       // (3)
       d = a;                       // (4)
       return c;                    // (5)
     }

     public static void main(String[] args) {
       String msg = f();
       System.out.println(msg);     // (6)
     }
   }

Select the one correct answer.

(a) The line marked (1).

(b) The line marked (2).

(c) The line marked (3).

(d) The line marked (4).

(e) The line marked (5).

(f) The line marked (6).

Q16 Which string, when inserted at (1), will not result in the same output as the other three strings?

import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class Q500_50 {
  public static void main(String[] args) {
    String index  = "0123456789012345678";
    String target = "JAVA JaVa java jaVA";
    Pattern pattern = Pattern.compile(_______________);  // (1)
    Matcher matcher = pattern.matcher(target);
    while(matcher.find()) {
      int startIndex = matcher.start();
      int endIndex = matcher.end();
      int lastIndex = startIndex == endIndex ? endIndex : endIndex-1;
      String matchedStr = matcher.group();
      System.out.print("(" + startIndex + "," + lastIndex + ":" +
                       matchedStr + ")");
    }
    System.out.println();
  }
}

Select the one correct answer.

(a) "[A-Za-z]+"

(b) "[a-zA-Z]+"

(c) "[A-Z]+[a-z]+"

(d) "[A-Z[a-z]]+"

Q17 Which method from the String or StringBuilder classes modifies the object on which it is invoked?

Select the one correct answer.

(a) The charAt() method of the String class.

(b) The toUpperCase() method of the String class.

(c) The replace() method of the String class.

(d) The reverse() method of the StringBuilder class.

(e) The length() method of the StringBuilder class.

Q18 Which statements are true, given the code new FileOutputStream("data", true) for creating an object of class FileOutputStream?

Select the two correct answers.

(a) FileOutputStream has no constructors matching the given arguments.

(b) An IOException will be thrown if a file named “data” already exists.

(c) An IOException will be thrown if a file named “data” does not already exist.

(d) If a file named “data” exists, its contents will be reset and overwritten.

(e) If a file named “data” exists, output will be appended to its current contents.

Q19 Which statement, when inserted at (1), will raise a runtime exception?

   class A {}

   class B extends A {}

   class C extends A {}

   public class Q3ae4 {
     public static void main(String[] args) {
       A x = new A();
       B y = new B();
       C z = new C();

       // (1) INSERT CODE HERE.
     }
   }

Select the one correct answer.

(a) x = y;

(b) z = x;

(c) y = (B) x;

(d) z = (C) y;

(e) y = (A) y;

Q20 Given the following program:

public class Q400_60 {
  public static void main(String[] args) {
    String str = "loop or not to loop";
    String[] strs = {"loop", "or", "not", "to", "loop"};
    // (1) INSERT LOOP HERE.
  }
}

Which code, when inserted at (1), will compile without errors?

Select the four correct answers.

(a) for (char ch : str)
  System.out.print(ch);
(b) for (char ch : str.toCharArray())
  System.out.print(ch);
(c) for (Character ch : str.toCharArray())
  System.out.print(ch);
(d) for (Character ch : str.toCharArray())
  System.out.print(ch.charValue());

(e) for (String str : strs)
  System.out.print(str);
(f) for (String elt : strs[])
  System.out.print(elt);
(g) for (String elt : strs)
  System.out.print(elt);
(h) for (Character ch : strs[str.length-1].toArray())
  System.out.print(ch);

Q21 A method within a class is only accessible by classes that are defined within the same package as the class of the method. How can such a restriction be enforced?

Select the one correct answer.

(a) Declare the method with the keyword public.

(b) Declare the method with the keyword protected.

(c) Declare the method with the keyword private.

(d) Declare the method with the keyword package.

(e) Do not declare the method with any accessibility modifiers.

Q22 Which code initializes the two-dimensional array matrix so that matrix[3][2] is a valid element?

Select the two correct answers.

(a) int[][] matrix = {
    { 0, 0, 0 },
    { 0, 0, 0 }
};
(b) int matrix[][] = new int[4][];
for (int i = 0; i < matrix.length; i++) matrix[i] = new int[3];
(c) int matrix[][] = {
    0, 0, 0, 0,
    0, 0, 0, 0,
    0, 0, 0, 0,
    0, 0, 0, 0
};
(d) int matrix[3][2];
(e) int[] matrix[] = { {0, 0, 0}, {0, 0, 0}, {0, 0, 0}, {0, 0, 0} };

Q23 Given the following directory structure:

   /proj
     |--- lib
     |    |--- supercharge.jar
     |
     |--- src
           |--- top
                 |--- sub
                       |--- A.java

Assume that the current directory is /proj/src, and that the class A declared in the file A.java uses reference types from the JAR file supercharge.jar.

Which commands will succeed without compile-time errors?

Select the two correct answers.

(a) javac -cp ../lib top/sub/A.java

(b) javac -cp ../lib/supercharge top/sub/A.java

(c) javac -cp ../lib/supercharge.jar top/sub/A.java

(d) javac -cp /proj/lib/supercharge.jar top/sub/A.java

(e) javac -cp /proj/lib top/sub/A.java

Q24 What will be the result of attempting to run the following program?

   public class Qaa75 {
     public static void main(String[] args) {
       String[][][] arr = {
           { {}, null },
           { { "1", "2" }, { "1", null, "3" } },
           {},
           { { "1", null } }
       };

       System.out.println(arr.length + arr[1][2].length);
     }
   }

Select the one correct answer.

(a) The program will terminate with an ArrayIndexOutOfBoundsException.

(b) The program will terminate with a NullPointerException.

(c) 4 will be written to standard output.

(d) 6 will be written to standard output.

(e) 7 will be written to standard output.

Q25 Which expressions will evaluate to true if preceded by the following code?

 String a = "hello";
 String b = new String(a);
 String c = a;
 char[] d = { 'h', 'e', 'l', 'l', 'o' };

Select the two correct answers.

(a) (a == "Hello")

(b) (a == b)

(c) (a == c)

(d) a.equals(b)

(e) a.equals(d)

Q26 Which statements are true about the following code?

   class A {
     public A() {}

     public A(int i) { this(); }
   }

   class B extends A {
     public boolean B(String msg) { return false; }
   }

   class C extends B {
     private C() { super(); }

     public C(String msg) { this(); }

     public C(int i) {}
   }

Select the two correct answers.

(a) The code will fail to compile.

(b) The constructor in A that takes an int as an argument will never be called as a result of constructing an object of class B or C.

(c) Class C defines three constructors.

(d) Objects of class B cannot be constructed.

(e) At most one of the constructors of each class is called as a result of constructing an object of class C.

Q27 Given two collection objects referenced by col1 and col2, which statements are true?

Select the two correct answers.

(a) The operation col1.retainAll(col2) will not modify the col1 object.

(b) The operation col1.removeAll(col2) will not modify the col2 object.

(c) The operation col1.addAll(col2) will return a new collection object, containing elements from both col1 and col2.

(d) The operation col1.containsAll(Col2) will not modify the col1 object.

Q28 Which statements are true about the relationships between the following classes?

   class Foo {
     int num;
     Baz comp = new Baz();
   }

   class Bar {
     boolean flag;
   }

   class Baz extends Foo {
     Bar thing = new Bar();
     double limit;
   }

Select the three correct answers.

(a) A Bar is a Baz.

(b) A Foo has a Bar.

(c) A Baz is a Foo.

(d) A Foo is a Baz.

(e) A Baz has a Bar.

Q29 Which statements are true about the value of a field, when no explicit assignments have been made?

Select the two correct answers.

(a) The value of a field of type int is undetermined.

(b) The value of a field of any numeric type is zero.

(c) The compiler may issue an error if the field is used in a method before it is initialized.

(d) A field of type String will denote the empty string ("").

(e) The value of all fields which are references is null.

Q30 Which statement is not true about the following two statements?

FileInputStream inputFile = new FileInputStream("myfile");        // (1)
FileOutputStream outputFile = new FileOutputStream("myfile");     // (2)

Select the one correct answer.

(a) Statement (1) throws a FileNotFoundException if the file cannot be found, or is a directory or cannot be opened for some reason.

(b) Statement (1) throws an IOException if the file cannot be found, or is a directory or cannot be opened for some reason.

(c) Statement (2) throws a FileNotFoundException if the file is a directory or cannot be opened for some reason.

(d) Statement (2) throws an IOException if the file is a directory or cannot be opened for some reason.

(e) Statement (2) creates a new file if one does not exist and appropriate permissions are granted.

(f) If the file opened by statement (2) already exists, its contents will be over-written.

Q31 Which statements describe guaranteed behavior of the garbage collection and finalization mechanisms?

Select the two correct answers.

(a) An object is deleted as soon as there are no more references that denote the object.

(b) The finalize() method will eventually be called on every object.

(c) The finalize() method will never be called more than once on an object.

(d) An object will not be garbage collected as long as it is possible for a live thread to access it through a reference.

(e) The garbage collector will use a mark and sweep algorithm.

Q32 Which main() method will succeed in printing the last program argument to the standard output and exit gracefully with no output if no program arguments are specified?

Select the one correct answer.

(a) public static void main(String[] args) {
  if (args.length != 0)
    System.out.println(args[args.length-1]);
}
(b) public static void main(String[] args) {
  try { System.out.println(args[args.length]); }
  catch (ArrayIndexOutOfBoundsException e) {}
}
(c) public static void main(String[] args) {
  int ix = args.length;
  String last = args[ix];
  if (ix != 0) System.out.println(last);
}
(d) public static void main(String[] args) {
  int ix = args.length-1;
  if (ix > 0) System.out.println(args[ix]);
}
(e) public static void main(String[] args) {
  try { System.out.println(args[args.length-1]); }
  catch (NullPointerException e) {}
}

Q33 Which statements are true about the interfaces in the Java Collections Framework?

Select the three correct answers.

(a) Set extends Collection.

(b) All methods defined in Set are also defined in Collection.

(c) List extends Collection.

(d) All methods defined in List are also defined in Collection.

(e) Map extends Collection.

Q34 What will be the result of compiling and running the following code?

public enum FrequentFlyer {
  PLATINUM(20), GOLD(10), SILVER(5), BASIC(0);
  private double extra;

  FrequentFlyer(double extra) {
    this.extra = extra;
  }

  public static void main (String[] args) {
    System.out.println(GOLD.ordinal() > SILVER.ordinal());
    System.out.println(max(GOLD,SILVER));

    System.out.println(max2(GOLD,SILVER));
  }

  public static FrequentFlyer max(FrequentFlyer c1, FrequentFlyer c2) {
    FrequentFlyer maxFlyer = c1;
    if (c1.compareTo(c2) < 0)
      maxFlyer = c2;
    return maxFlyer;
  }

  public static FrequentFlyer max2(FrequentFlyer c1, FrequentFlyer c2) {
    FrequentFlyer maxFlyer = c1;
    if (c1.extra < c2.extra)
      maxFlyer = c2;
    return maxFlyer;
  }
}

Select the one correct answer.

(a) The program will compile and print:

false
SILVER
GOLD

(b) The program will compile and print:

true
GOLD
SILVER

(c) The program will compile and print:

true
GOLD
GOLD

(d) The program will not compile, since the enum type FrequentFlyer does not implement the Comparable interface.

Q35 Given the following class declarations, which expression identifies whether the object referenced by obj was created by instantiating class B rather than classes A, C, and D?

   class A {}
   class B extends A {}
   class C extends B {}
   class D extends A {}

Select the one correct answer.

(a) obj instanceof B

(b) obj instanceof A && !(obj instanceof C)

(c) obj instanceof B && !(obj instanceof C)

(d) !(obj instanceof C || obj instanceof D)

(e) !(obj instanceof A) && !(obj instanceof C) && !(obj instanceof D)

Q36 What will be written to the standard output when the following program is executed?

   public class Qcb90 {
     int a;
     int b;
     public void f() {
       a = 0;
       b = 0;
       int[] c = { 0 };
       g(b, c);
       System.out.println(a + " " + b + " " + c[0] + " ");
     }

     public void g(int b, int[] c) {
       a = 1;
       b = 1;
       c[0] = 1;
     }

     public static void main(String[] args) {
       Qcb90 obj = new Qcb90();

       obj.f();
     }
   }

Select the one correct answer.

(a) 0 0 0

(b) 0 0 1

(c) 0 1 0

(d) 1 0 0

(e) 1 0 1

Q37 Given the following class, which statements are correct implementations of the hashCode() method?

   class ValuePair {
     public int a, b;
     public boolean equals(Object other) {
       try {
         ValuePair o = (ValuePair) other;
         return (a == o.a && b == o.b)
             || (a == o.b && b == o.a);
       } catch (ClassCastException cce) {
         return false;
       }
     }
     public int hashCode() {
       // (1) INSERT CODE HERE.
     }
   }

Select the three correct answers.

(a) return 0;

(b) return a;

(c) return a + b;

(d) return a - b;

(e) return a ^ b;

Q38 Given the following code:

class Interval<________________________> { // (1) INSERT TYPE CONSTRAINT HERE
  private N lower, upper;
  public void update(N value) {
    if (lower == null || value.compareTo(lower) < 0)
      lower = value;
    if (upper == null || value.compareTo(upper) > 0)
      upper = value;
  }
}

Which type constraints, when inserted at (1), will allow the class to compile?

Select the four correct answers.

(a) N extends Object

(b) N extends Comparable<N>

(c) N extends Object & Comparable<N>

(d) N extends Number

(e) N extends Number & Comparable<N>

(f) N extends Comparable<N> & Number

(g) N extends Integer

(h) N extends Integer & Comparable<N>

Q39 Which statements are true regarding the execution of the following code?

   public class Q3a0a {
     public static void main(String[] args) {
       int j = 5;

       for (int i = 0; i< j; i++) {
         assert i < j-- : i > 0;
         System.out.println(i * j);
       }
     }
   }

Select the two correct answers.

(a) An AssertionError will be thrown if assertions are enabled at runtime.

(b) The last number printed is 4, if assertions are disabled at runtime.

(c) The last number printed is 20, if assertions are disabled at runtime.

(d) The last number printed is 4, if assertions are enabled at runtime.

(e) The last number printed is 20, if assertions are enabled at runtime.

Q40 Which of the following method names are overloaded?

Select the three correct answers.

(a) The method name yield in java.lang.Thread

(b) The method name sleep in java.lang.Thread

(c) The method name wait in java.lang.Object

(d) The method name notify in java.lang.Object

Q41 What will be the result of attempting to compile and run the following program?

   public class Q28fd {
     public static void main(String[] args) {
       int counter = 0;
       l1:
       for (int i=0; i<10; i++) {
         l2:
         int j = 0;
         while (j++ < 10) {
           if (j > i) break l2;
           if (j == i) {
             counter++;
             continue l1;
           }
         }
       }
       System.out.println(counter);
     }
   }

Select the one correct answer.

(a) The program will fail to compile.

(b) The program will not terminate normally.

(c) The program will write 10 to the standard output.

(d) The program will write 0 to the standard output.

(e) The program will write 9 to the standard output.

Q42 Given the following interface declaration, which declaration is valid?

   interface I {
     void setValue(int val);
     int getValue();
   }

Select the one correct answer.

(a) class A extends I {
  int value;
  void setValue(int val) { value = val; }
  int getValue() { return value; }
}
(b) interface B extends I {
  void increment();
}

(c) abstract class C implements I {
  int getValue() { return 0; }
  abstract void increment();
}
(d) interface D implements I {
  void increment();
}
(e) class E implements I {
  int value;
  public void setValue(int val) { value = val; }
}

Q43 Which statements are true about the methods notify() and notifyAll()?

Select the two correct answers.

(a) An instance of the class Thread has a method named notify that can be invoked.

(b) A call to the method notify() will wake the thread that currently owns the lock of the object.

(c) The method notify() is synchronized.

(d) The method notifyAll() is defined in the class Thread.

(e) When there is more than one thread waiting to obtain the lock of an object, there is no way to be sure which thread will be notified by the notify() method.

Q44 Which statements are true about the correlation between the inner and outer instances of member classes?

Select the two correct answers.

(a) Fields of the outer instance are always accessible to inner instances, regardless of their accessibility modifiers.

(b) Fields of the outer instance can never be accessed using only the variable name within the inner instance.

(c) More than one inner instance can be associated with the same outer instance.

(d) All variables from the outer instance that should be accessible in the inner instance must be declared final.

(e) A class that is declared final cannot have any member classes.

Q45 What will be the result of attempting to compile and run the following code?

   public class Q6b0c {
     public static void main(String[] args) {
       int i = 4;
       float f = 4.3;
       double d = 1.8;
       int c = 0;
       if (i == f) c++;
       if (((int) (f + d)) == ((int) f + (int) d)) c += 2;
       System.out.println(c);
     }
   }

Select the one correct answer.

(a) The code will fail to compile.

(b) The value 0 will be written to the standard output.

(c) The value 1 will be written to the standard output.

(d) The value 2 will be written to the standard output.

(e) The value 3 will be written to the standard output.

Q46 Which operators will always evaluate all the operands?

Select the two correct answers.

(a) ||

(b) +

(c) &&

(d) ? :

(e) %

Q47 Which statement concerning the switch construct is true?

Select the one correct answer.

(a) All switch statements must have a default label.

(b) There must be exactly one label for each code segment in a switch statement.

(c) The keyword continue can never occur within the body of a switch statement.

(d) No case label may follow a default label within a single switch statement.

(e) A character literal can be used as a value for a case label.

Q48 Given the following code:

public class Q600_90 {
  public static void main(String[] args) {
    Scanner lexer = new Scanner("Treat!");
    if(lexer.hasNext("\w+")) {
      // (1)
    } else
      lexer.next();
    // (2)
    lexer.close();
    // (3)
  }
}

Where in the program can we independently insert the following print statement:

System.out.print(lexer.next());

in order for the program to compile and print the following output when run:

Treat!

Select the one correct answer.

(a) Insert the print statement at (1) only.

(b) Insert the print statement at (2) only.

(c) Insert the print statement at (3) only.

(d) None of the above.

Q49 Which of the following expressions are valid?

Select the three correct answers.

(a) System.out.hashCode()

(b) "".hashCode()

(c) 42.hashCode()

(d) ("4"+2).equals(42)

(e) (new java.util.ArrayList<String>()).hashCode()

Q50 Which statement regarding the following method definition is true?

   boolean e() {
     try {
       assert false;
     } catch (AssertionError ae) {
       return true;
     }
     return false; // (1)
   }

Select the one correct answer.

(a) The code will fail to compile, since catching an AssertionError is illegal.

(b) The code will fail to compile, since the return statement at (1) is unreachable.

(c) The method will return true, regardless of whether assertions are enabled at runtime or not.

(d) The method will return false, regardless of whether assertions are enabled at runtime or not.

(e) The method will return true if and only if assertions are enabled at runtime.

Q51 Which statement, when inserted at (1), will call the print() method in the Base class.

   class Base {
     public void print() {
       System.out.println("base");
     }
   }

   class Extension extends Base {
     public void print() {
       System.out.println("extension");

       // (1) INSERT CODE HERE.
     }
   }

   public class Q294d {
     public static void main(String[] args) {
       Extension ext = new Extension();
       ext.print();
     }
   }

Select the one correct answer.

(a) Base.print();

(b) Base.this.print();

(c) print();

(d) super.print();

(e) this.print();

Q52 Which statements are true about the following code?

   public class Vertical {
     private int alt;
     public synchronized void up() {
       ++alt;
     }
     public void down() {
       --alt;
     }
     public synchronized void jump() {
       int a = alt;
       up();
       down();
       assert(a == alt);
     }
   }

Select the two correct answers.

(a) The code will fail to compile.

(b) Separate threads can execute the up() method concurrently.

(c) Separate threads can execute the down() method concurrently.

(d) Separate threads can execute both the up() and the down() methods concurrently.

(e) The assertion in the jump() method will not fail under any circumstances.

Q53 Which parameter declarations can be inserted at (1) so that the program compiles without warnings?

interface Wagger{}
class Pet implements Wagger{}
class Dog extends Pet {}
class Cat extends Pet {}

public class Q100_51 {
  public static void main(String[] args) {
    List<Pet> p = new ArrayList<Pet>();
    List<Dog> d = new ArrayList<Dog>();
    List<Cat> c = new ArrayList<Cat>();
    examine(p);
    examine(d);
    examine(c);
  }

  static void examine(______________ pets) { // (1)
    System.out.print("Your pets need urgent attention.");
  }
}

Select the three correct answers.

(a) List<? extends Pet>

(b) List<? super Pet>

(c) List<? extends Wagger>

(d) List<? super Wagger>

(e) List<?>

(f) All of the above

Q54 What will be written to the standard output when the following program is run?

   public class Q03e4 {
     public static void main(String[] args) {
       String space = " ";

       String composite = space + "hello" + space + space;
       composite.concat("world");

       String trimmed = composite.trim();

       System.out.println(trimmed.length());
     }
   }

Select the one correct answer.

(a) 5

(b) 6

(c) 7

(d) 12

(e) 13

Q55 Given the following code, which statements are true about the objects referenced by the fields i, j, and k, given that any thread may call the methods a(), b(), and c() at any time?

   class Counter {
     int v = 0;
     synchronized void inc() { v++; }
     synchronized void dec() { v--; }
   }

   public class Q7ed5 {
     Counter i;
     Counter j;
     Counter k;
     public synchronized void a() {
       i.inc();
       System.out.println("a");
       i.dec();
     }

     public synchronized void b() {
       i.inc(); j.inc(); k.inc();
       System.out.println("b");
       i.dec(); j.dec(); k.dec();
     }

     public void c() {
       k.inc();
       System.out.println("c");
       k.dec();
     }
   }

Select the two correct answers.

(a) i.v is always guaranteed to be 0 or 1.

(b) j.v is always guaranteed to be 0 or 1.

(c) k.v is always guaranteed to be 0 or 1

(d) j.v will always be greater than or equal to k.v at any given time.

(e) k.v will always be greater than or equal to j.v at any given time.

Q56 Which method declarations, when inserted at (1), will not cause the program to fail during compilation?

   public class Qdd1f {
     public long sum(long a, long b) { return a + b; }

     // (1) INSERT CODE HERE.

   }

Select the two correct answers.

(a) public int sum(int a, int b) { return a + b; }

(b) public int sum(long a, long b) { return 0; }

(c) abstract int sum();

(d) private long sum(long a, long b) { return a + b; }

(e) public long sum(long a, int b) { return a + b; }

Q57 What will be the result of executing the following program code with assertions enabled?

   import java.util.LinkedList;

   public class Q4d3f {
     public static void main(String[] args) {
       LinkedList<String> lla = new LinkedList<String>();
       LinkedList<String> llb = new LinkedList<String>();
       assert lla.size() == llb.size() : "empty";

       lla.add("Hello");
       assert lla.size() == 1 : "size";

       llb.add("Hello");
       assert llb.contains("Hello") : "contains";
       assert lla.get(0).equals(llb.get(0)) : "element";
       assert lla.equals(llb) : "collection";
     }
   }

Select the one correct answer.

(a) Execution proceeds normally and produces no output.

(b) An AssertionError with the message "size" is thrown.

(c) An AssertionError with the message "empty" is thrown.

(d) An AssertionError with the message "element" is thrown

(e) An IndexOutOfBoundsException is thrown.

(f) An AssertionError with the message "container" is thrown.

Q58 What will be the result of compiling and running the following code?

public enum FrequentFlyerClass {
  PLATINUM(20), GOLD(10), SILVER(5), BASIC;
  private double extra;
  FrequentFlyerClass(double extra) {
    this.extra = extra;
  }

  public boolean equals(Object other) {
    if (this == other)
      return true;
    if (!(other instanceof FrequentFlyerClass))
      return false;
    return Math.abs(this.extra - ((FrequentFlyerClass) other).extra) < 0.1e-5;
  }

  public static void main (String[] args) {
    GOLD = SILVER;
    System.out.println(GOLD);
    System.out.println(GOLD.equals(SILVER));
  }
}

Select the one correct answer.

(a) The program will compile and print:

GOLD
false

(b) The program will compile and print:

SILVER
true

(c) The program will not compile, because of 3 errors in the program.

(d) The program will not compile, because of 2 errors in the program.

(e) The program will not compile, because of 1 error in the program.

Q59 Which constraint can be inserted at (1) so that the program compiles without warnings?

class NumClass <________________> { // (1)
  T numVal;
}

public class Q100_54 {
  public static void main(String[] args) {

    NumClass<Number> n1 = new NumClass<Number>();
    NumClass<Integer> n2 = new NumClass<Integer>();
  }
}

Select the one correct answer.

(a) T extends Integer

(b) T extends Number

(c) ? extends Number

(d) T super Number

(e) T super Integer

(f) ? super Integer

(g) None of the above

Q60 What will be the result of compiling and running the following program?

public class Varargs {
  public static <E> void print(E e, E...src) {
    System.out.print("|");
    for (E elt : src) {
      System.out.print(elt + "|");
    }
    System.out.println();
  }

  public static void main(String[] args) {
    String[] sa = {"9", "6"};
    print("9", "6");                 // (1)
    print(sa);                       // (2)
    print(sa, sa);                   // (4)
    print(sa, sa, sa);               // (5)
    print(sa, "9", "6");             // (6)
  }
}

Select the one correct answer.

(a) The program does not compile because of errors in one or more calls to the print() method.

(b) The program compiles, but throws a NullPointerException when run.

(c) The program compiles, and prints (where XXXXXXX is some hash code for the String class):

|9|6|
|6|
|
|[Ljava.lang.String;@XXXXXXX|[Ljava.lang.String;@XXXXXXX|
|9|6|

(d) The program compiles, and prints (where XXXXXXX is some hash code for the String class):

|6|
|
|9|6|
|[Ljava.lang.String;@XXXXXXX|[Ljava.lang.String;@XXXXXXX|
|9|6|

Q61 Given the following code:

package p1;
public enum Constants {
  ONE, TWO, THREE;
}
____________________________________________________
package p2;
// (1) INSERT IMPORT STATEMENTS HERE.
public class Q700_30 {
  public static void main(String[] args) {
    int value = new Random().nextInt(4);
    Constants constant = null;
    switch (value) {
      case 1:
        constant = ONE;
        break;
      case 2:
        constant = TWO;
        break;
      default:
        constant = THREE;
        break;
    }
    out.println(constant);
  }
}

Which import statements, when inserted at (1), will result in a program that prints a constant of the enum type Constants, when compiled and run?

Select the two correct answers.

(a) import java.util.*;
import p1.Constants;
import static p1.Constants.*;
import static java.lang.System.out;
(b) import java.util.*;
import static p1.Constants.*;
import static java.lang.System.out;
(c) import java.util.*;
import p1.Constants.*;
import java.lang.System.out;
(d) import java.util.*;
import p1.*;
import static p1.Constants.*;
import static java.lang.System.*;
(e) import java.util.Random;
import p1.*;
import static p1.Constants.*;
import System.out;

Q62 Given the following directory structure:

   /proj
     |--- bin
           |--- top
                 |--- sub

Assume that the classpath has the value:

top:top/sub

Which of the following statements are true?

Select the three correct answers.

(a) If the current directory is /proj/bin, the following directories are searched: top and sub.

(b) If the current directory is /proj/bin, the following directories are searched: bin, top and sub.

(c) If the current directory is /proj, the following directories are searched: bin, top and sub.

(d) If the current directory is /proj, no directories are searched.

(e) If the current directory is /proj/top, no directories are searched.

Q63 Given the following code:

package p1;
public enum Format {
  JPEG, GIF, TIFF;
}
____________________________________________________
package p1;
public class Util {
  public enum Format {
    JPEG { public String toString() {return "Jpeggy"; }},
    GIF  { public String toString() {return "Giffy"; }},
    TIFF { public String toString() {return "Tiffy"; }};
  }
  public static <T> void print(T t) {
    System.out.print("|" + t + "|");
  }
}
____________________________________________________
import static p1.Format.*;
import static p1.Util.Format;
import static p1.Util.print;

public class Importing {
  static final int JPEG = 200;
  public static void main(String[] args) {
    final int JPEG = 100;
    print(JPEG);
    print(____________.JPEG);
    print(____________.JPEG);
    print(p1._________.JPEG);
  }
}

Which sequence of names, when used top down in the main() method, will print:

|100||200||Jpeggy||JPEG|

Select the one correct answer.

(a) Format, Importing, Format

(b) Format, Format, Format

(c) Importing, Format, Format

Q64 Given the following code:

public class Q200_50 {
  public static void main(String[] args) {
    // (1) INSERT METHOD CALL HERE.
  }
  private static void widenAndBox(Long lValue){
    System.out.println("Widen and Box");
  }
}

Which method calls, when inserted at (1), will cause the program to print:

Widen and Box

Select the two correct answers.

(a) widenAndBox((byte)10);

(b) widenAndBox(10);

(c) widenAndBox((long)10);

(d) widenAndBox(10L);

Q65 What will the program print when compiled and run?

public class Q200_80 {
  public static void main(String[] args) {
    callType(10);
  }

  private static void callType(Number num){
    System.out.println("Number passed");
  }

  private static void callType(Object obj){
    System.out.println("Object passed");
  }
}

Select the one correct answer.

(a) The program compiles and prints: Object passed

(b) The program compiles and prints: Number passed

(c) The program fails to compile, because the call to the callType() method is ambiguous.

(d) None of the above.

Q66 What will the program print when compiled and run?

import java.util.ArrayList;
import java.util.List;

public class Q400_70 {
  public static void main(String[] args) {
    List<Integer> list = new ArrayList<Integer>();
    list.add(2007); list.add(2008); list.add(2009);
    System.out.println("Before: " + list);
    for (int i : list) {
      int index = list.indexOf(i);
      list.set(index, ++i);
    }
    System.out.println("After: " + list);
  }
}

Select the one correct answer.

(a) Before: [2007, 2008, 2009]
After:  [2008, 2009, 2010]
(b) Before: [2007, 2008, 2009]
After:  [2010, 2008, 2009]
(c) Before: [2007, 2008, 2009]
After:  [2007, 2008, 2009]
(d) Before: [2007, 2008, 2009]
After:  [2008, 2009, 2007]
(e) The program throws a java.util.ConcurrentModificationException when run.

Q67 Which method implementation will write the given string to a file named “file", using UTF8 encoding?

Select the one correct answer.

(a) public void write(String msg) throws IOException {
  FileWriter fw = new FileWriter(new File("file"));
  fw.write(msg);
  fw.close();
}
(b) public void write(String msg) throws IOException {
  OutputStreamWriter osw = new OutputStreamWriter(
                               new FileOutputStream("file"), "UTF8");
  osw.write(msg);
  osw.close();
}
(c) public void write(String msg) throws IOException {
  FileWriter fw = new FileWriter(new File("file"));
  fw.setEncoding("UTF8");
  fw.write(msg);
  fw.close();
}

(d) public void write(String msg) throws IOException {
  FilterWriter fw = new FilterWriter(
                        new FileWriter("file"), "UTF8");
  fw.write(msg);
  fw.close();
}
(e) public void write(String msg) throws IOException {
  OutputStreamWriter osw = new OutputStreamWriter(
                               new OutputStream(new File("file")), "UTF8");
  osw.write(msg);
  osw.close();
}

Q68 Given the following code:

public class Person {
  protected transient String name;
  Person() { this.name = "NoName"; }
  Person(String name) { this.name = name; }
}
____________________________________________________
public class Student extends Person { protected long studNum;
  Student() { }
  Student(String name, long studNum) {
    super(name);
    this.studNum = studNum;
  }
}
____________________________________________________
import java.io.Serializable;
public class GraduateStudent extends Student implements Serializable {
  private int year;
  GraduateStudent(String name, long studNum, int year) {
    super(name, studNum);
    this.year = year;
  }

  public String toString() {
    return "(" + name + ", " + studNum + ", " + year + ")";
  }
}
____________________________________________________
import java.io.*;
public class Q800_60 {

  public static void main(String args[])
                     throws IOException, ClassNotFoundException {
    FileOutputStream outputFile = new FileOutputStream("storage.dat");
    ObjectOutputStream outputStream = new ObjectOutputStream(outputFile);
    GraduateStudent stud1 = new GraduateStudent("Aesop", 100, 1);
    System.out.print(stud1);

    outputStream.writeObject(stud1);
    outputStream.flush();
    outputStream.close();

    FileInputStream inputFile = new FileInputStream("storage.dat");
    ObjectInputStream inputStream = new ObjectInputStream(inputFile);
    GraduateStudent stud2 = (GraduateStudent) inputStream.readObject();
    System.out.println(stud2);
    inputStream.close();
  }
}

Which statement is true about the program?

Select the one correct answer.

(a) It fails to compile.

(b) It compiles, but throws an exception at runtime.

(c) It prints (Aesop, 100, 1)(NoName, 0, 1).

(d) It prints (Aesop, 100, 1)(Aesop, 100, 1).

(e) It prints (Aesop, 100, 1)(null, 0, 1).

Q69 The following program formats a double value in the US locale, and prints the result 1,234.567. Complete the program using the code snippets given below:

import _________________;
import _________________;

public class FormattingNumbers {
  public static void main(String[] args) {
    double d = 1234.567;
    _____________ f = _______________(_____________);
    System.out.println(______________);
  }
}

Any snippet may be used multiple times.

java.text.NumberFormat               NumberFormat
java.util.NumberFormat               DateFormat
java.text.Locale                     Format
java.util.Locale

NumberFormat.getNumberInstance       Locale.US
NumberFormat.getCurrencyInstance     DateFormat.DOUBLE
DateFormat.getInstance               NumberFormat.US
new NumberFormat

d.format(f)                          f.formatNumber(d)
f.format(d)                          NumberFormat.format(d)

Q70 Given the following program:

import java.util.Arrays;
public class Q500_100 {
  public static void main(String[] args) {
    String[] tokens = ___(1)___.split(___(2)___);
    System.out.println(Arrays.toString(tokens));
  }
}

Which pair of strings, when inserted at (1) and (2), respectively, will result in the following output:

[, mybook, mychapter, , mysection]

Select the two correct answers.

(a) "mybookmychapter\mysection", "\"

(b) "\mybook\mychapter\mysection", "\"

(c) "\mybook\mychapter\\mysection\", "\\"

(d) "\mybook\mychapter\\mysection\\", "\\"

(e) "\mybook\mychapter\mysection", "\"

(f) The program will not compile, regardless of which alternative from (a) to (e) is inserted.

(g) The program will throw an exception when run, regardless of which alternative from (a) to (e) is inserted.

Q71 Given the following code:

public class Q600_30 {
  public static void main(String[] args) {
    // (1) INSERT STATEMENT HERE
  }
}

Which statements, when inserted at (1), will print the following:

|false|

Select the six correct answers.

(a) System.out.printf("|%-4b|", false);

(b) System.out.printf("|%5b|", false);

(c) System.out.printf("|%.5b|", false);

(d) System.out.printf("|%4b|", "false");

(e) System.out.printf("|%3b|", 123);

(f) System.out.printf("|%b|", 123.45);

(g) System.out.printf("|%5b|", new Boolean("911"));

(h) System.out.printf("|%2b|", new Integer(2007));

(i) System.out.printf("|%1b|", (Object[])null);

(j) System.out.printf("|%1b|", (Object)null);

(k) System.out.printf("|%3$b|", null, 123, true);

Q72 Which statements are true about the classes SupA, SubB and SubC?:

class SupA<T> {
  public List<?> fuddle() { return null; }
  public List scuddle(T t) { return null; }
}

class SubB<U> extends SupA<U> {
  public List fuddle() { return null;}
  public List<?> scuddle(U t) { return null; }
}

class SubC<V> extends SupA<V> {
  public List<V> fuddle() { return null;}
  public List<? extends Object> scuddle(V t) { return null; }
}

Select the four correct answers.

(a) Class SubB will not compile.

(b) Class SubC will not compile.

(c) Class SubB will compile.

(d) Class SubC will compile.

(e) Class SubB overloads the methods in class SupA.

(f) Class SubC overloads the methods in class SupA.

(g) Class SubB overrides the methods in class SupA.

(h) Class SubC overrides the methods in class SupA.

Annotated Answers

Q1 (a), (b), (c), and (e)

Only local variables need to be explicitly initialized before use. Fields are assigned a default value if not explicitly initialized.

Q2 (d)

A try block must be followed by at least one catch or finally block. No catch blocks can follow a finally block. Methods need not declare that they can throw Runtime Exceptions, as these are unchecked exceptions.

Q3 (e)

Giving parameters (2, 3) to the method substring() constructs a string consisting of the characters between positions 2 and 3 of the original string. The positions are indexed in the following manner: position 0 is immediately before the first character of the string, position 1 is between the first and the second character, position 2 is between the second and the third character, and so on.

Q4 (a)

A Thread object executes the run() method of a Runnable object on a separate thread when started. A Runnable object can be given when constructing a Thread object. If no Runnable object is supplied, the Thread object (which implements the Runnable interface) will execute its own run() method. A thread is initiated using the start() method of the Thread object.

Q5 (a), (b), (c)

First, note that nested packages or nested static members are not automatically imported.

In (d), p2.DefenceInDepth is not a static member and therefore cannot be imported statically.

With (e), March.LEFT becomes ambiguous because both the second and the third import statement statically import March. The enum constant LEFT cannot be resolved either, as its enum type March cannot be resolved.

With (f), the enum constant LEFT cannot be resolved, as none of the static import statements specify it.

The enum type p2.March is also not visible outside the package.

Q6 (c)

The loop prints out the values 12, 9, 6, and 3 before terminating.

Q7 (e)

The fact that a field is static does not mean that it is not accessible from non-static methods and constructors. All fields are assigned a default value if no initializer is supplied. Local variables must be explicitly initialized before use.

Q8 (e)

All the "hello" literals denote the same String object. Any String object created using the new operator will be a distinct new object.

Q9 (a)

Calls to the methods suspend(), sleep(), and wait() do not stop a thread. They only cause a thread to move out of its running state. A thread will terminate when the execution of the run() method has completed.

Q10 (b), (d)

(a) The class need not be declared as a generic type if it defines any generic methods.

(b) The method choose(T, T), where T extends Comparable<T>, is not applicable to the arguments (Integer, String). Note that Object is not Comparable<Object>.

(c) The method choose(T, T), where T extends Comparable<T>, is not applicable to the arguments (Integer, Double). Note that Number is not Comparable<Number>.

(d) The actual type parameter Double specified in the method call also requires that the int argument is cast to a double in order for the call to be valid. The method choose(T, T), where T extends Comparable<T>, is then applicable to the argument list (Double, Double).

(e) Cannot convert the Double returned by the method to an int using a cast.

(f) The method returns a Double which is first converted to a double, which in turn is converted to an int.

Q11 (e)

An object of the class Extension is created. The first thing the constructor of Extension does is invoke the constructor of Base, using an implicit super() call. All calls to the method void add(int) are dynamically bound to the add() method in the Extension class, since the actual object is of type Extension. Therefore, this method is called by the constructor of Base, the constructor of Extension, and the bogo() method with the parameters 1, 2, and 8, respectively. The instance field i changes value accordingly: 2, 6, and 22. The final value of 22 is printed.

Q12 (d)

TreeMap and HashSet do not maintain an ordered sequence of objects. Vector and ArrayList require shifting of objects on insertion and deletion, while LinkedList does not. When objects are frequently inserted and deleted from the middle of the sequence, LinkedList gives the best performance.

Q13 (a) and (d)

Field b of the outer class is not shadowed by any local or inner class variables, therefore, (a) will work. Using this.a will access the field a in the inner class. Using this.b will result in a compilation error, since there is no field b in the inner class. Using Q4a39.this.a will successfully access the field of the outer class. The statement c = c will only reassign the current value of the local variable c to itself.

Q14 (b), (c), (d)

The class File does not have methods called found, isAFile, or isADirectory.

Q15 (d)

At (1), a new String object is constructed by concatenating the string "bye" in the String object denoted by b and the string "!". After line (2), d and b are aliases. After line (3), b and a are aliases, but d still denotes the String object with "bye" from line (0). After line (4), d and a are aliases. Reference d no longer denotes the String object created in line (0). This String object has no references to it and is, therefore, a candidate for garbage collection.

Q16 (c)

The regex in (c) requires a sequence of uppercase letters to be followed by a sequence of lowercase letters. The other regexes are equivalent, as they require a sequence which can consist of upper and/or lower case letters, i.e., any combination of letters.

Running the program with the regex in (c) will produce the following output:

(5,6:Ja)(7,8:Va)

Running the program with the other regexes will produce the following output:

(0,3:JAVA)(5,8:JaVa)(10,13:java)(15,18:jaVA)

Q17 (d)

String objects are immutable. None of the methods of the String class modify a String object. Methods toUpperCase() and replace() in the String class will return a new String object that contains the modified string. However, StringBuilder objects are mutable.

Q18 (e)

The second parameter to the constructor specifies whether the file contents should be replaced or appended when the specified file already exists.

Q19 (c)

Statement (a) will work just fine, and (b), (d), and (e) will cause compilation errors. Statements (b) and (e) will cause compilation errors because they attempt to assign an incompatible type to the reference. Statement (d) will cause compilation errors, since a cast from B to C is invalid. Being an instance of B excludes the possibility of being an instance of C. Statement (c) will compile, but will throw a runtime exception, since the object that is cast to B is not an instance of B.

Q20 (b), (c), (d), (g)

In (a), a String is neither an array nor an Iterable. In (e), the local variable str is redeclared. In (f) the occurrence of the array operator [] is not permissible. In (h), the String class does not have a method called toArray, but it has a method called toCharArray.

Q21 (e)

The desired accessibility is package accessibility, which is the default accessibility for members that have no accessibility modifier. The keyword package is not an accessibility modifier and cannot be used in this context.

Q22 (b) and (e)

For the expression matrix[3][2] to access a valid element of a two-dimensional array, the array must have at least four rows and the fourth row must have at least three elements. Fragment (a) produces a 2 × 3 array. Fragment (c) tries to initialize a two-dimensional array as a one-dimensional array. Fragment (d) tries to specify array dimensions in the type of the array reference declaration.

Q23 (c), (d)

The pathname of the JAR file, together with the JAR file name, should be specified.

Q24 (a)

The expression arr.length will evaluate to 4. The expression arr[1] will access the element { { "1", "2" }, { "1", null, "3" } }, and arr[1][2] will try to access the third sub-element of this element. This produces an ArrayIndexOutOfBoundsException, since the element has only two sub-elements.

Q25 (c) and (d)

String objects can have identical sequences of characters. The == operator, when used on String object references, will just compare the references and will only return true when both references denote the same object (i.e., are aliases). The equals() method will return true whenever the contents of the String objects are identical. An array of char and a String are two totally different types and cannot be compared using the equals() method of the String class.

Q26 (b) and (c)

Statement (d) is false, since an object of B can be created using the implicit default constructor of the class. B has an implicit default constructor since no constructor has explicitly been defined. Statement (e) is false, since the second constructor of C will call the first constructor of C.

Q27 (b) and (d)

The retainAll(), removeAll(), and addAll() methods do not return a new collection object, but instead modify the collection object they were called upon. The collection object given as an argument is not affected. The containsAll() does not modify either of the collection objects.

Q28 (b), (c), and (e)

An instance of the class Baz is also an instance of the class Foo, since the class Baz extends the class Foo. A Baz has a Bar since instances of the class Baz contain an instance of the class Bar by reference. A Foo has a Baz, since instances of the class Foo contain an instance of the class Baz by reference. Since a Foo has a Baz which has a Bar, a Foo has a Bar.

Q29 (b) and (e)

Unlike local variables, all fields are initialized with default initial values. All numeric fields are initialized to zero, boolean fields to false, char fields to 'u0000', and all reference fields to null.

Q30 (b), (d)

Q31 (c) and (d)

Very little is guaranteed about the behavior of the garbage collection and finalization mechanisms. The (c) and (d) statements are two of the things that are guaranteed.

Q32 (a)

The main() method in (b) will always generate and catch an ArrayIndexOutOfBounds-Exception, since args.length is an illegal index in the args array. The main() method in (c) will always throw an ArrayIndexOutOfBoundsException since it is also uses args.length as an index, but this exception is never caught. The main() method in (d) will fail to print the argument if only one program argument is supplied. The main() method in (e) will generate an uncaught ArrayIndexOutOfBoundsException if no program arguments are specified.

Q33 (a), (b), and (c)

Set and List both extend Collection. A map is not a collection and Map does not extend Collection. Set does not have any new methods other than those defined in Collection. List defines additional methods to the ones in Collection.

Q34 (a)

All enum types implement the Comparable interface. Comparison is based on the natural order, which in this case is the order in which the constants are specified, with the first one being the smallest. The ordinal value of the first enum constant is 0, the next one has the ordinal value 1, and so on.

Q35 (c)

The important thing to remember is that if an object is an instance of a class, it is also an instance of all the superclasses of this class.

Q36 (e)

Method g() modifies the field a. Method g() modifies the parameter b, not the field b, since the parameter declaration shadows the field. Variables are passed by value, so the change of value in parameter b is confined to the method g(). Method g() modifies the array whose reference value is passed as a parameter. Change to the first element is visible after return from the method g().

Q37 (a), (c), and (e)

The equals() method ignores the ordering of a and b when determining if two objects are equivalent. The hashCode() implementation must, therefore, also ignore the ordering of a and b when calculating the hash value, i.e., the implementation must return the same value even after the values of a and b are swapped.

Q38 (b), (c), (e), (g)

(a) N is not Comparable.

(b) Ok

(c) Ok. N is Comparable. Specifying Object as a bound is superfluous in this case.

(d) N is not Comparable, as Number is not Comparable.

(e) Ok. N is Number and Comparable.

(f) The class must be specified first in multiple bounds.

(g) Ok. N is Integer and Integer is Comparable, N is Comparable<Integer>.

(h) N is Integer and Integer is Comparable<Integer>, N is Comparable<Integer>. The class cannot implement the same interface, in this case Comparable, more than once.

Q39 (c) and (d)

The variable j is only decremented if assertions are enabled. The assertion never fails, since the loop condition ensures that the loop body is only executed as long as i<j is true. With assertions enabled, each iteration decrements j by 1. The last number printed is 20 if assertions are disabled at runtime, and the last number printed is 4 if assertions are enabled at runtime.

Q40 (b) and (c)

These names have overloaded methods that allow optional timeout values as parameters.

Q41 (a)

The program will fail to compile since the label l2 cannot precede the declaration int j = 0. For a label to be associated with a loop, it must immediately precede the loop construct.

Q42 (b)

Classes cannot extend interfaces, they must implement them. Interfaces can extend other interfaces, but cannot implement them. A class must be declared abstract if it does not provide an implementation for one of its methods. Methods declared in interfaces are implicitly public and abstract. Classes that implement these methods must explicitly declare their implementations public.

Q43 (a) and (e)

The notify() and notifyAll() methods are declared in the class Object. Since all other classes extend Object, these methods are also available in instances of all other classes, including Thread. The method notify() is not synchronized, but will throw an IllegalMonitorStateException if the current thread is not the owner of the object lock.

Q44 (a) and (c)

Accessing fields of the outer instance using only the variable name works within the inner instance as long as the variable is not shadowed. Fields need not be declared final in order to be accessible within the inner instance.

Q45 (a)

The code will fail to compile because the literal 4.3 has the type double. Assignment of a double value to a float variable without an explicit cast is not allowed. The code would compile and write 0 to standard output when run, if the literal 4.3 was replaced with 4.3F.

Q46 (b) and (e)

The && and || operators exhibit short-circuit behavior. The first operand of the ternary operator (? :) is always evaluated. Based on the result of this evaluation, either the second or the third operand is evaluated.

Q47 (e)

No labels are mandatory (including the default label), and can be placed in any order within the switch body. The keyword continue may occur within the body of a switch statement as long as it pertains to a loop. Any constant non-long integral value can be used for case labels as long as the type is compatible with the expression in the switch expression.

Q48 (d)

The condition of the if statement will always be false, as the string pattern "\w+" will not match the first token "Treat!". No matter what we insert at (1), it will not be executed. The else part will always be executed, retrieving the current token with the next() method, thereby exhausting the output.

Inserting at (2) will mean attempting to tokenize from an exhausted input, resulting in a java.util.NoSuchElementException. Inserting at (3) means calling the next() method after closing the scanner, resulting in a java.lang.IllegalStateException.

Q49 (a), (b), and (e)

Expressions (a), (b), and (e) all call the method hashCode() on valid objects. (c) is an illegal expression, as methods cannot be called on primitive values. The call in (d) to the equals() method requires an object as argument.

Q50 (e)

The method returns true if and only if assertions are enabled at runtime. It will only return false if assertions are disabled.

Q51 (d)

Overridden method implementations are accessed using the super keyword. Statements like print(), Base.print(), and Base.this.print() will not work.

Q52 (c) and (d)

Executing synchronized code does not guard against executing non-synchronized code concurrently.

Q53 (a), (c), (e)

Lists of type Pet, Dog, and Cat are subtypes of List<? extends Pet>, List<? extends Wagger> and List<?>.

List<? super Pet> is a supertype for a list of Pet itself or a supertype of Pet, e.g., Wagger, but not Dog and Cat.

List<? super Wagger> is a supertype for a list of Wagger itself or a supertype of Wagger, e.g., Object, but not Pet, Dog, and Cat.

Q54 (a)

Strings are immutable, therefore, the concat() method has no effect on the original String object. The string on which the trim() method is called consists of 8 characters, where the first and the two last characters are spaces (" hello "). The trim() method returns a new String object where the white space characters at each end have been removed. This leaves the 5 characters of the word "hello".

Q55 (a) and (b)

If a thread is executing method b() on an object, it is guaranteed that no other thread executes methods a() and b() concurrently. Therefore, the invocation counters i and j will never show more than one concurrent invocation. Two threads can concurrently be executing methods b() and c(). Therefore, the invocation counter k can easily show more than one concurrent invocation.

Q56 (a) and (e)

Declaration (b) fails, since the method signature only differs in the return type. Declaration (c) fails, since it tries to declare an abstract method in a non-abstract class. Declaration (d) fails, since its signature is identical to the existing method.

Q57 (a)

Execution proceeds normally and produces no output. All assertions are true.

Q58 (c)

The program will not compile, because the method equals() cannot be overridden by enum types.

The program will not compile, because the enum constant GOLD cannot be assigned a new value. The constants are final.

The program will not compile, because the enum constant BASIC cannot be created, as no explicit default constructor is defined.

Q59 (b)

None of the formal type parameter specifications with a wildcard are permitted. This rules out (c) and (f). The keyword super can only be used with a wildcard, and therefore rules out (d) and (e). NumClass<Number> is not a subtype of NumClass<T extends Integer>, ruling out (a).

Q60 (d)

Note that the print() method does not print its first argument. The vararg is passed in the method calls as follows:

   print("9", "6");                 // (1) new String[] {"6"}
   print(sa);                       // (2) new String[] {}
   print(sa, sa);                   // (4) sa
   print(sa, sa, sa);               // (5) new String[][] {sa, sa}
   print(sa, "9", "6");             // (6) new String[] {"9", "6"}

Q61 (a), (d)

In the program, we need to import the types java.util.Random and the enum type p1.Constants. We also need to statically import the constants of the enum type p1.Constants, and the static field out from the type java.lang.System. All classes must be fully qualified in the import statements. Only (a) and (d) fit the bill.

(b) does not import the enum type p1.Constants. (c) does not import the enum type p1.Constants either. In addition, it does not statically import the constants of the enum type p1.Constants and the static field out from the type java.lang.System. (e) does not statically import the static field out from the type java.lang.System.

Q62 (a), (d), (e)

Note that the entries in the classpath are relative paths.

When the current directory is /proj/bin, both entries in the classpath can be found under /proj/bin. The directory bin itself is not searched, as there is no valid path / proj/bin/bin.

When the current directory is /proj, both entries in the classpath cannot be found relative to /proj, i.e., the paths /proj/top and /proj/top/sub are not valid paths.

Q63 (c)

We need to access the following:

Importing.JPEG (to print 200)

p1.Util.Format.JPEG (to print "Jpeggy"). Since p1.Util.Format is statically imported by the second import statement, we need only specify Format.JPEG.

p1.Format.JPEG (to print "JPEG"), which is explicitly specified to distinguish it from other JPEG declarations. The first import statement is actually superfluous.

Q64 (c), (d)

Only primitive types allow automatic widening conversion, wrapper types do not allow automatic widening conversion. A byte or an int cannot be automatically converted to a Long. Automatic boxing and unboxing is only allowed between corresponding primitives types and their wrapper classes.

Q65 (b)

The method with the most specific signature is chosen. In this case the int argument 10 is converted to an Integer which is passed to the Number formal parameter, as type Number is more specific than Object.

Q66 (b)

First note that the indexOf() method returns the index of the first occurrence of its argument in the list. Although the value of variable i is successively changing during the execution of the loop, it is the first occurrence of this value that is replaced in each iteration:

                                     0      1     2
                              [2007, 2008, 2009]
After iteration 1: [2008, 2008, 2009]
After iteration 2: [2009, 2008, 2009]
After iteration 3: [2010, 2008, 2009]

Note also that we are not removing or adding elements to the list, only changing the reference values stored in the elements of the list.

Q67 (b)

Method implementation (a) will write the string to the file, but will use the native encoding. Method implementation (c) will fail to compile, since a method named setEncoding does not exist in class FileWriter. Method implementation (d) will fail to compile, since FilterWriter is an abstract class that cannot be used to translate encodings. Method implementation (e) will fail to compile, since class OutputStream is abstract.

Q68 (c)

Note that only GraduateStudent is Serializable. The field name in the Person class is transient. During serialization of a GraduateStudent object, the fields year and stud-Num are included as part of the serialization process, but not the field name. During deserialization, the default constructors of the superclasses up the inheritance hierarchy of the GraduateStudent class are called, as none of the superclasses are Serializable.

Q69 The completed program is as follows:

import java.text.NumberFormat;
import java.util.Locale;

public class FormattingNumbers {
  public static void main(String[] args) {
    double d = 1234.567;
    NumberFormat f = NumberFormat.getNumberInstance(Locale.US);
    System.out.println(f.format(d));
  }
}

Q70 (c), (d)

The output shows two empty strings (first and third). In order to split on the back-slash (), the required string is "\\". Remember that is a metacharacter for both Java strings and for regexes. We need to escape in the regex specification, which requires \. In order to escape these two backslashes in a Java string, we need to add a backslash for each backslash we want to escape in the regex, i.e., "\\".

In the input string we need to escape each backslash so that it is not interpreted as a metacharacter.

The split() method tokenizes the input on the regex, but it does not return trailing empty strings. Therefore, the empty strings matched by the backslashes at the end of the input are not reported. The method call str.split(regex) is equivalent to Pattern.compile(regex).split(str).

Q71 (a), (b), (c), (g), (i), (j)

(a) 5 character positions will be used. The width 4 is overridden, and the - sign is superfluous.

(b) 5 character positions will be used. The width 5 is superfluous.

(c) The precision 5 is the same as the length of the resulting string, and therefore superfluous.

(d) The reference value of the string literal "false" is not null, resulting in "true" being printed. Analogous reasoning for (e) and (f).

(g) Since the argument to the Boolean constructor is not "true", the value represented by the wrapper object is false.

(h) Same as (d).

(i) Since the argument is null, the value printed is "false". Width specification is overridden by the length of the string "false". Same for (j).

(k) The third argument is true, therefore "true" is printed.

Q72 (c), (d), (g), (h)

The method header signature of the corresponding methods are the same after erasure, i.e. List fuddle() and List scuddle(Object). The return type of overriding methods can be a raw type or a parameterized type.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset