Friday, May 15, 2009

Java Mock Exam Questions with detailed answers

Q1     Given:

 class J {
  private static int notFinalized;
  public static int notFinalized() {return notFinalized;}
  private K k;
  private int name;
  public int name() {return name;}
  public J(K k, int i) {this.k = k; name = i; notFinalized++;}
  public void finalize() {
    synchronized (k) {
      System.out.print(name);
      notFinalized--;
      k.notify();
    }
  }
}

class K {
  private void m1() {
    J j = null;
    for (int i = 0; i < 5; i++) {
      j = new J(this, i);       // 1
    }
    Runtime.getRuntime().gc();  // 2
    synchronized (this) {
      while (J.notFinalized() > 0) {
        try {wait();} catch (InterruptedException ie) {}
      }
    }
  }
  public static void main(String[] args) {
    new K().m1();
  }
}


When the processing of line 2 begins how many objects of type J that were created at line 1 are eligible for garbage collection?

    (1)     0
    (2)     1
    (3)     4
    (4)     5
    (5)     Can not be determined without more information
    (6)     Compiler error
    (7)     Run time error
    (8)     None of the above
       
    Answer : 3
    Explanation :

 Method K.m1 creates five objects of type J. Each instance has a name represented by an integer between 0 and 4 inclusive.
If the garbage collector does not run then the program will produce no output.If the garbage collector does run then the output of the program could be a series of integers that are the names of four of the five objects.
As each new object is created its reference is assigned to the reference variable j.The previously referenced object then becomes eligible for garbage collection. The last object created, 4, is not available for garbage collection until method m1 runs to completion.
The while loop in the synchronized block will never complete because J.notFinalized will never return zero.
 This program is intended to provide a working example of garbage collecting objects referenced by local variables.
       
Q2    What is the output of the following code when compiled and run? Select two correct answers


1 public class Sample {
2    public static void main(String[] args){
3        int y=0;               
4        int x=z=1;   
5        System.out.println(y+","+x+","+z);
6    }
7 }



    (1)     Prints 0,1,1
    (2)     Error during compilation at line 3
    (3)     Prints 0,0,1
    (4)     Error during compilation at line 4
    (5)     Error during compilation at line 5
       
    Answer : 4,5
    Explanation :

Variable z is not declared, thus, z cannot be resolved on lines 2 and 3. In Java, z cannot be declared that way. In order to get this code to compile, we have to write either:
int z=1,x=z;
Or
int z=1;
int x=z;
Or
int z=1;
int x=1;
       
Q3     What is the output of the following code when compiled and run? Select one correct answer


1 public class Sample {
2    public static void main(String[] args){
3        int j = 017;
4        int i = (byte)j >> 2;
5        System.out.println(Integer.toBinaryString(i));
6    }
7 }



    (1)     Prints 3
    (2)     Error during compilation at line 4
    (3)     Error during compilation at line 5
    (4)     Prints 11
    (5)     Prints 0
       
    Answer : 4
    Explanation :

First off, 017 is an octal integer literal having the decimal value 15. Second, the cast to byte only applies to j and not to j >> 2 as a whole. Thus, j is downcast to byte and then upcast to int again before the shifting.Briefly, the cast has no effect here. Then, the binary sequence of 15 is 00000000 00000000 00000000 00001111, which, shifted 2 bits to the right, yields 00000000 00000000 00000000 00000011. Finally, the binary sequence, 11, is printed. Note that the prefixed 0's are dismissed.
       
Q4    Select three correct statements:

    (1)     The garbage collection thread cannot outlive the last user thread
    (2)     The garbage collection can be forced by invoking System.gc().
    (3)     The garbage collection thread is a non-deamon thread
    (4)     The finalize() method is invoked at most once by the JVM for any given object
    (5)     The finalize() method may resurrect the object upon which it has been invoked
       
    Answer : 1,4,5
    Explanation :

The garbage collection thread is a deamon thread. The latter die when there are no more users threads running. The garbage collection cannot be forced.
       
Q5     What is the output of the following code when compiled and run? Select one correct answer.

import java.io.*;
public class Mohit{
    public static void main(String[] args) {
        MohitSub myref = new MohitSub();
        try{
            myref.test();
        }catch(IOException ioe){}
    }
    void test() throws IOException{
        System.out.println("In Mohit");
        throw new IOException();
    }
}
class MohitSub extends Mohit {
    void test() {
        System.out.println("In MohitSub");
    }
}



    (1)     Prints:

    In MohitSub

    (2)     Prints:

    In Mohit

    (3)     Prints:

    In Mohit
        In MohitSub

    (4)     Prints:

    In MohitSub
        In Mohit

    (5)     The code does not compile
       
    Answer : 5
    Explanation :

The code does not compile because no IOException is thrown when invoking myref.test(). Note that myref's declared and runtime types are MohitSub and thus no dynamic lookup will be performed. However, if you change the declared type to Mohit, the code will compile and the correct answer would be A because method test() isoverridden in MohitSub
       
Q6    What is the output of the following code when compiled and run with the following command line: java Friends two three? Select two correct answers.

public class Friends {
    public static void main(String[] args) throws Exception {
        int i=2;
        boolean b = true;
        throw new Exception("Values are:"+(b!=b)+","+(i=args.length)+","+(b=i==2));
    }
}



    (1)     The exception message is Values are:false,3,true
    (2)     The exception message is Values are:true,2,false
    (3)     The exception message is Values are:false,2,true
    (4)     The final value of b is false
    (5)     An exception is thrown at runtime
       
    Answer : 3,5
    Explanation :

Do not mix b!=b and b=!b. In the former, we check if b's value is different from b's value (?!) which is clearly false. In the latter, we assign b's opposite value to itself, that is, if b is true, then after b=!b, b ends up being false.Moreover, be aware that b=i==2 is evaluated as b=(i==2) because operator = has the lowest precedence. Finally, note that the arguments to the Exception constructor are evaluatedfrom the left to the right. First, b!=b is evaluated, then i=args.length (args.length is 2, so i keeps its value), and finally, b=i==2.
       
    Q7    Select two correct statements about the code given below?


class A{}
class B extends A implements E{}    //line 1
class C extends A{}
class D extends B{}
interface E{}
public class Question07 {
    public static void main(String[] args) {
        A a = new D();    //line 2
        C c = new C();    //line 3
        E e = (E)a;    //line 4
        B b = (B)e;    //line 5
    }
}



    (1)     The code compiles without error and runs fine
    (2)     Compilation error on line 1 because interface E is not yet declared (forward-referencing)
    (3)     Compilation error on line 4 because class A does not implement interface E
    (4)     The cast on line 4 is mandatory
    (5)     The cast on line 5 is not mandatory
       
    Answer : 1,4
    Explanation :

First, pay attention to the class hierarchy (B and C are sibling classes!!) Then, there is no such thing as forward-referencing issues when using interfaces declared later in the compilation unit.On line 4, we are dealing with an object whose runtime type is D which implements interface E. The cast is mandatory, though, since the reference type (A) is not assignmentcompatible with the reference type E. The cast on line 5 is mandatory for the same reasons.
       
Q8     How many objects are eligible for garbage collection immediately after line 1? Select one correct answer.


public class HomeGC {
    public static void main(String[] args) {
        HomeGC tGC = new HomeGC();
        tGC.doSomething();    //line 1
        Thread.sleep(20000);
    }

    public void doSomething(){
        Object[] objArray = new Object[2];
        for(int i = 0 ; i < objArray.length ; i++) {
            objArray[i] = new Object();
        }
    }
}



    (1)     0
    (2)     1
    (3)     2
    (4)     3
    (5)     4
       
    Answer : 4
    Explanation :

We declare an array of Object of length two. We then initialize each element to a new Object. We have 2 objects in the array and the array itself (which is an object, too!), that makes 3.
       
Q9     What is the output of the following code when compiled and run? Select one correct answer.


public class ABC {
    public static void main(String[] args) {
        try {
            int i = (int)(Math.random()*10);
            if(i<=5)
                System.out.println("i = "+i);
            else
                throw new Exception("i > 5");
        } catch (Exception e){
            System.err.println(e.getMessage()+" (i="+i+")");
        }
    }
}



    (1)     The output cannot be determined
    (2)     Compilation error
    (3)     An exception is thrown at runtime
    (4)     Output is i = 2
    (5)     Output is i > 5 (i=6)
       
    Answer : 2
    Explanation :

The code does not compile because i (declared in the try block!) is not in scope when accessed from the catch block.
       
Q10     What is the output of the following code when compiled and run? Select one correct answer.


public class ABCSample {
    public static void main(String[] args) {
        new ABCSample().doSomething();
    }

    public void doSomething(){
        int i=5;
        Thread t = new Thread(new Runnable(){
            public void run(){
                for(int j=0;j<=i;j++){
                    System.out.print(" "+j);
                }
            }
        });
        t.start();
    }
}



    (1)     Prints 0 1 2 3 4
    (2)     Compilation error
    (3)     No output
    (4)     IllegalThreadStateException is thrown at runtime
    (5)     Prints 0 1 2 3 4 5
       
    Answer : 2
    Explanation :

The code does not compile because the anonymous inner class (new Runnable(){...}) tries to access the non-final local variable i.

Search Amazon for Best Books on Java J2EE

Blogarama

blogarama - the blog directory

Search your favourite topics

Google