OCPJP 6 Mock Exam -16

SHARE & COMMENT :

1 . What will be the output?

 import java.util.*;
 public class Pippin {
   public static void main(String argv[]){
     TreeMap tm = new TreeMap();
     tm.put("one", new Integer(1));
     tm.put("two",new Integer(3));
     tm.put("three",new Integer(2));
     Iterator it = tm.keySet().iterator();
     while(it.hasNext()){
        Integer iw = tm.get(it.next());
        System.out.print(iw);
     }
  }

}

Choose the one below:

  1. Compile time error at line 10
  2. Compilation and output of 123
  3. Compilation and output of the digits “1″, “2″ and “3″, but the order can’t be determined
  4. Compilation and output of onetwothree
  5. Compilation but runtime error at line 10

2 . The following is part of the code for an application that will run two time consuming processes in two Threads. We want to be sure that all threads get a chance to run.Which statement at line 9 will accomplish this?

  public class TestQ20 implements Runnable {

   public static void main (String[] args){
     new Thread( new TestQ20() ).start();
    // start some other process here
   }
   public void run(){
     for( int i = 0 ; i < 1000 ; i++ ){
      // select statement to go here
       someComplexProcess();
     }
  }
  // remaining methods
 }

Choose the one below:

  1. Thread.currentThread().yield();
  2. Thread.sleep(50);
  3. yield();
  4. Thread.yield();

3 . What will be the output?

 public class TechnoSample {
  public static void main (String[] args){
    TechnoSample tq = new DerivedSample();
    ((DerivedSample)tq).echoN( tq.paramA );
  }
  int paramA = 9 ;
 }

 class DerivedSample extends TechnoSample {
   int paramA = 3 ;
   void echoN( int n ){
    System.out.println("number is " + n );
  }
 }

Choose the one below:

  1. Output of “number is 3″
  2. Output of “number is 9″
  3. A compiler error due to the cast in line 4
  4. A compiler error in line 3 due to the lack of a constructor for DerivedSample

4 . You have a working class ClassA that has a method declared as follows:

protected float calculate( int x, int y )

Now you have to extend ClassA with ClassB and override the calculate method with a new version. This new calculate will have to call the processB() method which has the following declaration, where MyException is a custom Exception extending Exception.

protected float processB( int x ) throws MyException

What features should your overriding calculate method in ClassB have?

  1. Define new calculate so that MyException is handled by printing an error mesg:
    protected float calculate(int x, int y){
    try{
    processB(x);
    catch(Exception e){
    System.out.println(“ClassB.calculate throws ” + e);
    }
  2. Declare the new calculate this way:
    protected float calculate( int x, int y ) throws MyException
  3. No special exception handling is needed, just make the new calculate private
    private float calculate(int x, int y)
  4. Declare the new calculate this way:
    public float calculate(int x, int y) throws RuntimeException

5 . The general contract for the hashCode method states that under certain conditions, the hashCode method for a given object must always produce the same int value as long as data that affects operation of the equals method remains the same?

Choose the one below:

  1. During the execution of a single program
  2. Every execution of the program on a given machine
  3. Every execution of the program using a given SDK version
  4. Every execution of the program on any SDK version from 1.4.0 on

6 . The following code fragments show various uses of the key word synchronized. Which of them could be used to protect a resource against modification by multiple Threads at the same time?

  1. public synchronized class BankAccount {
    // methods and variables to be protected
    }
  2. public synchronized void adjustBalance( float f ){
    // variables to be protected are modified here
    }
  3. public void adjustBalance( float f ){
    synchronized(f){
    //variables to be protected are modified here
    }
    }
  4. private Object lock = new Object();
    public void adjustBalance(float f){
    synchronized(lock){
    // variables to be protected are modified here
    }
    }

7 . Which of the following statements are true?

  1. A call to a method that throws an exception must always be enclosed in a try/catch block
  2. Variables created within a try or catch block will be local to that block
  3. A try statement must always be matched with a catch statement
  4. A finally block may not contain try/catch statements

8 . The strictfp modifier can be applied to what Java entities?

  1. a class
  2. a method
  3. a variable
  4. a code block within a method

9 . Which of the following statements about inner classes is incorrect?

  1. An inner class can have the same name as the enclosing class
  2. An anonymous inner class can only be declared as implementing a single interface
  3. An instance of an inner class that is not static or in a static context can always reference the associated instance of the enclosing class
  4. All anonymous inner classes have Object as their immediate superclass

10 . The following diagram shows the relationship between some classes you have to work with. Note that BaseWidget is declared abstract and that FastWidget is the only class that implements Runnable?

Object
  + BaseWidget (abstract)
      +-- SlowWidget
      +-- FastWidget (implements Runnable)

The options show signatures of various methods in another class. Choose the methods you would be able to call with an instance of SlowWidget?

  1. methodA(Object obj)
  2. methodB(BaseWidget bw)
  3. methodC(Runnable rr)
  4. methodD(FastWidget fw)
  5. methodE(SlowWidget sw)

11 . The following code has a nested class named Nested. What is the proper format to declare and create an instance of Nested in the main method?

 public class TopLevel {

   public static void main (String[] args){
     // what goes here?
     System.out.println("Created " + nt );
   }

   static class Nested {
      String id ;
     Nested( String s ){ id = s ; }
   } // end Nested
 }

Choose the one below:

  1. Nested nt = new Nested(“one”);
  2. TopLevel.Nested nt = new Nested(“two”);
  3. Nested nt = new TopLevel().new Nested(“three”);
  4. TopLevel.Nested nt = new TopLevel().new Nested(“four”);

12 . Which of the following are valid uses of the assert statement?

  1. assert (i > 10) : System.out.print(“i is bigger than 10″);
  2. assert (i > 10);
  3. assert (i > 10) : “i is bigger than 10″;
  4. assert (i = 10);

13 . Consider the following outline of the declaration of a normal class with an inner class?

public class NormClass {
  long startTime ;

  public class NestedClass {
       // methods and variables of NestedClass
  }
   // other methods and variables of NormClass
}

Which of the following can be used by a method inside NestedClass to refer to the startTime variable in the enclosing instance of NormClass?

  1. this.startTime
  2. NormClass.this.startTime
  3. this.NormClass.startTime
  4. startTime

14 . What will be the output?

import java.util.*;
public class Laxton{
  public static void main(String argv[]){
    HashMap hm = new HashMap();
    hm.put("1","one");
    hm.put("2","two");
    hm.put("3","one");
    Iterator it = hm.keySet().iterator();
    while(it.hasNext()){
        System.out.print(it.next());
    }
  }
}

Choose the one below:

  1. Compile time error, the HashMap class has an add method not a put method
  2. Compilation but runtime error due to attempt to add duplicate element
  3. Compilation and output of onetwothree
  4. Compilation and output of 123
  5. Compilation and output of 1, 2 and 3 but in an indetermined order

15 . Which of the following are public variables or methods that belong to an instance of Thread?
Do not select static methods or deprecated methods?

  1. yield() method
  2. stop() method
  3. run() method
  4. toString() method
  5. priority – an int variable

16 . What will be the output?

public class TechnoSample {
  public static void main (String[] args){
    int j ;
    for( int i = 10, j = 0 ; i > j ; j++ ){
      i = i - 1 ;
    }
    // Statement can go here
  }
}

Choose the one below:

  1. The loop initializer uses the correct form to set the values of i and j
  2. The loop initializer is not legal and the code will not compile for that reason
  3. If we put the following statement after the loop, it would report “i = 5 j = 5″
    System.out.println(“i = ” + i + ” j = ” + j );
  4. If we put the following statement after the loop, it would report “j = 5″
    System.out.println( “j = ” + j );

17 . Which of the following statements are true?

  1. The TreeMap class implements the Collection interface
  2. The Vector class allows elements to be accessed using the get(int offset) method
  3. The TreeSet class stores values in sorted order and ensures that the values are unique
  4. The elements in the LinkedHashMap are kept in sorted order

18 . The GenericFruit class declares the following method to return a float number of calories in the average serving size?

public float aveCalories( )

Your Apple class, which extends GenericFruit, overrides this method.
In a DietSelection class which extends Object, you want to use the GenericFruit method on an Apple object instead of the method in the Apple class.

Select the correct way to finish the statement in the following code fragment so that the GenericFruit version of aveCalories is called using the gf reference.

 GenericFruit gf = new Apple();
 float cal = // finish this statement using gf

Choose the one below:

  1. gf.aveCalories();
  2. ((GenericFruit)gf).aveCalories();
  3. gf.super.aveCalories();
  4. There is no way to use gf to call the GenericFruit method

19 . What will be the output?

class FrequencyException extends Exception{
  public String getMessage(){
    return "Frequency Exception";
  }
}
public class Note{
  public static void main(String argv[]){
    Note n = new Note();
    System.out.print(n.tune());
  }
  public int  tune(){
    try{
        return play(444);
    }catch(Exception e){
        System.out.println(e.getMessage());
    }catch(FrequencyException fe){
        System.out.println(fe.getMessage());

    }finally{
        return 2;
    }
  }
  public  int  play(int iFrequency)throws FrequencyException{
    return 1;
  }
}

Choose the one below:

  1. Compile time error problem with catch statements
  2. Compilation and output of 2
  3. Compilation and output of 1
  4. Compile time error, Exception class is final
  5. Compile time error fault with method call after return statement

20 . You have a class, MyThing, that implements a finalize method. You have a method which creates a MyThing array and fills it with MyThing objects. When all of the contents of the array become eligible for garbage collection, which of the following statements about the process of garbage collection are true?

  1. The first MyThing created, as the oldest, will be collected first
  2. The last MyThing created, as the youngest, will be collected first
  3. Java does not guarantee the order of collection
  4. The finalize method of each MyThing will be run as soon as the garbage collection mechanism determines it is unreachable

21 . What will be the output?

public class TestQ38 {
 public static void main (String[] args){
    Object obj = buildTest( 3 ) ;
    System.gc();
    System.out.println("exiting");
 }

 public static TestQ38 buildTest(int n ){
   TestQ38 t = null ;
   for( int i = 0 ; i < n ; i++ ){
    t = new TestQ38( i ) ;
   }
   return t ;
 }

 String name ;
 public TestQ38( int n ){
   name = "Number " + n ;
 }

 public void finalize(){
  System.out.print("finalize " + name ) ;
 }
}

Choose the one below:

  1. It does not compile due to incorrect signature of the finalize method
  2. It compiles but no text is written when it runs due to incorrect signature of the finalize method
  3. Before “exiting” is written, 2 messages from finalize will be printed
  4. Before “exiting” is written, 3 messages from finalize will be printed

22 . Which of the following statements about wrapper classes is correct?

  1. Each wrapper class for an integer primitive, such as Integer and Long, has a max and a min method
  2. The Math class has static max and min methods for integer primitives
  3. Each wrapper class for an integer primitive, such as Integer and Long, has one or more methods to parse values out of Strings
  4. The Math class provides static String parsing methods for all integer primitves

23 . What will be the output?

public class Test {
    int iTime=7;
    public static void main(String argv[]){
        Test t = new Test();
        t.calc(10);
    }
    public void calc(int iTime){
     start:
        for(int i =0; i < 2; i++){
            if(i >1){
                break start;
                System.out.println(iTime);
            }
            System.out.print(i);
            System.out.print(iTime);
        }
    }
}

Choose the one below:

  1. Compile time error
  2. Compilation and output of 010110
  3. Compilation and output of 0717
  4. Compilation and endless output of 010110

24 . What will be the output?

public class Test {

 public static final StringBuffer style =
      new StringBuffer("original");

 public static void main (String[] args){
   Test tq = new Test();
   tq.modify( style );
   System.out.println("Now " + style );
 }

 public void modify( StringBuffer sb ){
    sb.append(" is modified" );
 }
}

Choose the one below:

  1. Compiler objects to modification of a static final variable
  2. Output of “Now original”
  3. Output of “Now original is modified”
  4. Output of “Now is modified”

25 . Consider the variables declared in the following code:

public class Test {

 static Object theObj ;
 static Object[] someObj ;
 static String letters[] = {"A", "B", "C", "D" };
 static char[] caps = {'A', 'B', 'C', 'D' };

 public static void main (String[] args){
   someObj = new Object[ 3 ] ;
   int[] theInts = null ;
   // what can go here?
 }

Select the statements that would cause a compiler error when used to replace the comment?

  1. theObj = letters;
  2. someObj = letters;
  3. theInts = (int[]) caps;
  4. theObj = theInts;

26 . Which three are true for class java.util.ArrayList?

  1. It can contain duplicates
  2. Its methods are thread-safe
  3. Can be iterated bi-directionally
  4. It implements java.util.Set
  5. It is well-suited for fast random access
  6. It implements java.util.Collections

27 . What will be the output?

  public class TechnoSample {
   public static void main(String [] args) {
     double num = 7.4;
     int a = (int) Math.abs(num + .5);
     int b = (int) Math.ceil(num + .5);
     int c = (int) Math.floor(num + .5);
     int d = (int) Math.round(num + .5);
     int e = (int) Math.round(num - .5);
     int f = (int) Math.floor(num -.5);
    int g = (int) Math.ceil(num -.5);
    int h = (int) Math.abs(num - .5);

    System.out.println("" + a + b + c + d + e + f + g + h);
  }
 }

Choose the one below:

  1. 56
  2. 78787676
  3. 78788777
  4. 77787776
  5. Compilation fails
  6. An exception is thrown at runtime

28 . What will be the output?

 int i=3, j=0, result=1;
 result += i-- * --j ;
 System.out.println( result );

Choose the one below:

  1. 0
  2. -1
  3. -2
  4. -3
  5. Compilation fails
  6. An exception is thrown at runtime

29 . How can you destroy an object?

  1. null all the references to the object
  2. call Runtime.getRuntime().gc
  3. set all of the object’s references to null
  4. call x.remove() , where x is the object’s name
  5. call x.finalize() , where x is the object’s name
  6. only the garbage collection system can destroy an object

30 . What will be the output?

 class Bool {
   static boolean b;
  public static void main(String [] args) {
      int x=0;
      if (b ) {
       x=1;
      }
      else if (b = false) {
       x=2;
     }
     else if (b) {
      x=3;
     }
     else {
      x=4;
     }
     System.out.println("x = " + x);
   }
 }

Choose the one below:

  1. x = 0
  2. x = 1
  3. x = 2
  4. x = 3
  5. x = 4
  6. Compilation fails

31 . Which concrete class provides the specified features?

The presence of a mapping for a given key within this collection instance will not prevent the key from being recycled by the garbage collector.

Choose the one below:

  1. Vector
  2. Hashtable
  3. TreeMap
  4. TreeSet
  5. HashMap
  6. HashSet
  7. WeakHashMap
  8. None of the above

32 . What will be the output?

class A extends Thread {
  public void run() {
    try {
      synchronized (this) {
        wait();
      }
    } catch (InterruptedException ie) {
      System.out.print(interrupted());
    }
  }
  public static void main(String[] args) {
    A a1 = new A();
    a1.start();
    a1.interrupt();
  }
}

Choose the one below:

  1. Prints: true
  2. Prints: false
  3. Compiler error
  4. Run time error
  5. None of the above

33 . What will be the output?

class C {
  public static void main(String[] args) {
    Boolean b1 = Boolean.valueOf(true);
    Boolean b2 = Boolean.valueOf(true);
    Boolean b3 = Boolean.valueOf("TrUe");
    Boolean b4 = Boolean.valueOf("tRuE");
    System.out.print((b1==b2) + ",");
    System.out.print((b1.booleanValue()==b2.booleanValue()) + ",");
    System.out.println(b3.equals(b4));
  }
}

Choose the one below:

  1. Prints: false,false,false
  2. Prints: false,true,true
  3. Prints: true,false,false
  4. Prints: true,false,true
  5. Prints: true,true,false
  6. Prints: true,true,true
  7. Compile-time error
  8. Run-time error

34 . Which of the follow are true statements?

  1. An anonymous class can extend only the Object class
  2. An anonymous class can not implement an interface
  3. An anonymous class can be abstract
  4. An anonymous class is implicitly final
  5. An anonymous class can be static
  6. The class instance creation expression for an anonymous class must never include parameters
  7. An anonymous class must declare at least one constructor
  8. None of the above

35 . What will be the output?

	abstract class TechnoSuper {
		abstract void TechnoMethod();
	}

	class TechnoSub extends TechnoSuper {
		void TechnoMethod();
	}

Choose the one below:

  1. TechnoSuper TSup = new TechnoSuper();
  2. TechnoSuper TSup = new TechnoSub();
  3. None of the above

36 . Given the following code, which of the following options if inserted after the comment //here will allow the code to compile without error?

interface Remote{
    public void  test();

}
public class Moodle{
    public static void main(String argv[]){
	Moodle m = new Moodle();
    }
    public void go(){
	//here
    }
}

Choose the one below:

  1. Remote r = new Remote(){ public void test(){} };
  2. Remote remote = new Remote();
  3. test();
  4. this.main();

37 . What will be the output?

public class Flip{
    public static void main(String argv[]){
	System.out.println(~4);
   }
}

Choose the one below:

  1. Compile time error
  2. Compilation and output of 11
  3. Compilation and output of -4
  4. Compilation and output of -5

38 . What will be the output?

public class Mickle  extends Thread implements Runnable{
    public static void main(String argv[]){
	Mickle m = new Mickle();
	m.start();

    }
    public void run(){
	go();
    }
     public void  go(){
	int i;
	while(true){
	    try{
		wait();
		System.out.println("interrupted");
	    }catch (InterruptedException e) {}
	}

    }
}

Choose the one below:

  1. Compile time error
  2. Compilation but runtime exception
  3. Compilation but no output at runtime
  4. Compilation and output of “interrupted” at runtime

39 . Given the following code, which of the options if inserted after the comment //here will allow the code to compile without error?

class Wchapel{
    String sDescription = "Aldgate";
    public String  getDescription(){
	return "Mile End";
    }
    public void output(int i ){
	System.out.println(i);
    }
}
interface Liz{

}
public class Wfowl extends Wchapel implements Liz{
    private int i = 99;
    public static void main(String argv[]){
	Wfowl wf = new Wfowl();
	wf.go();
    }
    public void go(){
	//here

    }
}

Choose the one below:

  1. super().output(100);
  2. new Wfowl().output(i);
  3. class test implements Liz{}
  4. System.out.println(sDescription);
  5. new Wfowl();
  6. getDescription();

40 . Which of the following statements are true of the HashMap class?

  1. It does not permit null values
  2. It does not permit null keys
  3. It stores information as key/value pairs
  4. Elements are returned in the order they were added

41 . Which of the following statements are true?

  1. Interface methods cannot be static
  2. Interface methods must have a return type of void
  3. An interface cannot extend another class
  4. An interface method cannot be marked as final

42 . “If two objects return the same hashCode value they must be equal according to the equals method”.
True Or False?

  1. True
  2. False

43 . Which of the following statements are true?

  1. An overriden method must have the same return type as the version in the parent class
  2. An overriden method must throw the same exceptions as the version in the parent class
  3. An overriden method must have the same method parameter types and names as that in the parent version
  4. An overriden method cannot be less visible than the version in the parent class

44 . What will be the output?

public class Tux extends Thread{
	static String sName = "vandeleur";
	public static void main(String argv[]){
		Tux t = new Tux();
		t.piggy(sName);
		System.out.println(sName);
	}
	public void piggy(String sName){
		sName = sName + " wiggy";
		start();
		}
	public void run(){
		for(int i=0;i < 4; i++){
			sName = sName + " " + i;
	        }
	}
 }

Choose the one below:

  1. Compile time error
  2. Compilation and output of “vandeleur wiggy”
  3. Compilation and output of “vandeleur wiggy 0 1 2 3″
  4. Compilation and probably output of “vandelur” but possible output of “vandeleur 0 1 2 3″

45 . Suppose we have two classes defined as follows:

class Base extends Object implements Runnable
class Derived extends Base implements Observer

Two variables created as follows:

Base base = new Base();
Derived derived = new Derived();

Which of the Java code fragments will compile and execute without errors?

  1. Object obj = base;
    Runnable run = obj;
  2. Object obj = base;
    Runnable run = (Runnable) obj;
  3. Object obj = base;
    Observer ob = (Observer) base;
  4. Object obj = derived;
    Observer ob2 = obj;

46 . What will be the output?

  public class EqualsTest {
    public static void main(String[] args) {
      Long L = new Long(5);
      Integer I = new Integer(5);
      if (L.equals(I))  System.out.println("Equal");
      else System.out.println("Not Equal");
    }
  }

Choose the one below:

  1. compiles and prints “Equal”
  2. compiles and prints “Not Equal”
  3. compilation error at line 5
  4. run time cast error at line 5

47 . What will be the output?


  public class Base extends Object {
    String objType;
    public Base() {
        objType = "Base";
    }
  }

  public class Derived extends Base {
    public Derived() {
       objType = "Derived";
   }
   public static void main(String[] args) {
       Derived derived = new Derived();
   }
 }

Choose the one below:

  1. Two class files, Base.class and Derived.class will be created
  2. Compilation error at line 1
  3. Compilation error at line 8

48 . Trying to compile the following source code produces a compiler warning to the effect that the variable ‘tmp’ may not have been initialized?

  class Demo {
      String msg = "Type is ";
      public void showType(int n) {
          String tmp;
          if (n > 0) tmp = "positive";
          System.out.println(msg + tmp);
      }
  }

Choose the one below:

  1. 4 String tmp = null;
  2. 4 String tmp = “”;
  3. Insert line: 6 else tmp = “negative”;
  4. Remove line 4 and insert a new line after 2 as follows:
    3 String tmp;

49 . The greek letter Pi in the Unicode used by Java has the value 3c0 in hexadecimal representation.
Write the Unicode literal which would be used to initialize a char variable to Pi. Just write the Unicode literal char, not the complete expression. In other words, what should replace XXXX in the following statement?

char PiChar = XXXX;

50 . The following method definition is designed to parse and return an integer from an input string which is expected to look like “nnn, ParameterName”. In the event of a NumberFormatException, the method is to return -1?

  public int getNum(String S) {
    try {
      String tmp = S.substring(0, S.indexOf(','));
      return (Integer.parseInt(tmp));
    } catch(NumberFormatException e) {
        System.out.println("Problem in " + tmp);
    }
    return -1;
  }

What happens when we try to compile this code and execute the method with an input string which does not contain a comma (,) separating the number from the text data?

  1. Compilation error @line 6
  2. Prints the error message to standard output and returns -1
  3. A NullPointerException is thrown @line 3
  4. A StringIndexOutOfBoundsException is thrown @line 3

Answers

1 : 1 is correct.
Explanation:
(1)(2) & (3) The compiler realizes that the get returns an Object reference which needs a cast to type Integer. (4) Even if the cast was supplied to fix the compile error, the outputwould be the integer values, not the keys. (5) The need for a cast is found by the compiler so E does not occur.

2 : 1 & 4 is correct.
Explanation:
(1) This works because yield is a static method of the Thread class, although the currentThread call is not necessary (2) You can’t use sleep without providing for anInterruptedException (3) This does not work because the TestQ20 class does not extend Thread (4) This works because yield is a static method of the Thread class.(Credit: LanWrights)

3 : 2 is correct.
Explanation:
(1) No, the compiler uses paramA in the TechnoSample class, not DerivedSample (2) The address of paramA is fixed at compile time based on the TechnoSample reference type so thevalue found is 9 (3) No, this cast is perfectly legal and essential to get the code to compile (4) No, the compiler provides a default constructor. (Credit: LanWrights)

4 : 1 is correct.
Explanation:
(1) Handling the exception internally is the only option that works (2) The compiler won’t let you use an overriding method that declares a checked exception when the original methoddoes not (3) This does not solve anything. In addition to the exception problem, you can’t declare an overriding method that is more private than the original (4) You can’t changethe exception type by the throws declaration, the compiler will reject this. (Credit: LanWrights)

5 : 1 is correct.
Explanation:
The contract only requires that the same value be returned during one execution. Thus a hashcode should never be assumed to be the same between executions.

6 : 2 & 4 is correct.
Explanation:
(1) Wrong because you can’t label a class as synchronized (2) This would work by locking the object during the entire adjustBalance method (3) Wrong for several reasons, 1. youcan’t synchronize on a primitive, and 2. f is a local variable (4)This would work by using the separate “lock” Object as a synchronization flag during execution of thesynchronized code block. (Credit: LanWrights)

7 : 2 is correct.
Explanation:
(1) No, a call to a method that throws an exception may itself be in a method that throws that exception or if the Exception is a descendent of RuntimException it need notcatch the exception at all (2) Yes, as with other types of code blocks, a variable created in a try or catch block is local to that block (3) No, a try statement may be matchedwith a finally statement without a catch block (4) A finally block may contain its own try/catch statement and it is common in Java programming to put in such a construct.

8 : 1 & 2 is correct.
Explanation:
(1) The strictfp modifier can be applied to an entire class. It forces all floating-point operations in the class to adhere to the strict standard (2) When applied to a method,all floating point expressions in the method will use the strict standard (3) No, strictfp can only be used with an entire class, an interface or a method (4) No, strictfp canonly be used with an entire class, an interface or a method.

9 : 1 & 4 is correct.
Explanation:
(1) Yes, this statement is incorrect, inner classes are forbidden to have the same name as the enclosing class (4) Yes, this statement is incorrect, anonymous inner classes mayextend a variety of classes. (2) & (3) are not correct.

10 : 1,2 & 5 is correct.
Explanation:
(1) Certainly, any reference can be cast to Object(2) Yes, any reference can be cast to a superclass, the fact that BaseWidget is abstract does not alter this (3) No, SlowWidgetcan’t be cast to Runnable, only FastWidget could (4) No, FastWidget is not a superclass of SlowWidget (5) Certainly.

11 : 1 & 2 is correct.
Explanation:
(1) This works because Nested is a static member of TopLevel so it does not need an instance. However, outside the TopLevel class you would need the form shown in b (2) Thisworks because the full name of Nested is TopLevel.Nested – you could use this form outside the TopLevel class (3) This is an incorrect constructor, as a static member of TopLevel,Nested does not need an instance (4) This is an incorrect constructor, as a static member of TopLevel, Nested does not need an instance.

12 : 2 & 3 is correct.
Explanation:
(1) incorrect because the System.out.print method has a return type of void which is not allowed after the : of an assert statement (2) a valid assert statement (3) a validassert statement (4) incorrect because the assert statement must check that something is true, and the code given performs an assignment returning an int primitive.

13 : 2 & 4 is correct.
Explanation:
(1) No, this refers to a member of the inner class (2) Yes, although needlessly convoluted, NormClass.this refers to the enclosing object (3) No, this is backwards (4) Yes, thesimplest way since the inner class can access all instance members directly.

14 : 5 is correct.
Explanation:
(1) No, HashMap has the put(key, object) method required by the Map interface (2) There is no error, Map does not care about duplicate elements (3) No, the Iterator accesses thekeys, which are “1″, “2″ and “3″ (4) Although these are the key Strings, the order is not guaranteed (5) Yes, the HashMap class stores elements as key/value pairs but the order ofkeys is not guaranteed.

15 : 3 & 4 is correct.
Explanation:
(1) No, yield is a static method (2) No, stop is a deprecated instance method (3) Yes, run is a instance method (4) Yes, every object has a toString method (5) No, the priorityvariable is a private instance variable.

16 : 2 is correct.
Explanation:
(1) No, this is not the correct form, see (2). (2) Right, this is not a correct initializer because it combines declaring and setting the variable j which is already definedin the method (3) Even if the loop initializer was fixed, the variable i is out of scope and can’t be used (4) The program can’t compile and run as shown.

17 : 2 & 3 is correct.
Explanation:
(1) No, TreeMap implements the Map interface (2) Yes, Vector has the get( index ) method as required by the List interface (3) Yes, TreeSet implements the SortedSet interface, whichensures that the values are unique and store in the “natural order” of the elements (4) The elements in the LinkedHashMap are held in order of addition, not sorted.

18 : 4 is correct.
Explanation:
(1) wrong because the runtime resolution of method calls finds the Apple method (2) wrong because this extra cast does not change the object type (3) does not create a valid Javastatement (4) correct, there is no way for a class outside the GenericFruit hierarchy to call the GenericFruit method using an Apple reference.

19 : 1 is correct.
Explanation:
(1) Catch statments must proceed from most specific to most general, thus Exception must always be the last exception type caught. (2) See (1), but note that if the catch orderwas fixed, the finally clause would be executed and 2 returned. (3) See (1) & (2). (4) No, of course not (5) No, this syntax is fine.

20 : 3 is correct.
Explanation:
(1) & (2) see (3). (3) The Java Language Specification does not guarantee anything about the order in which objects are collected (4) Running the finalize method can be separatefrom the mechanism that determines an object is unreachable so the order can’t be guaranteed.

21 : 3 is correct.
Explanation:
(1) Even if this was the wrong signature, it would not prevent compilation. (2) This is the correct signature for the finalize method so it will run when objects are garbagecollected. (3) Only 2 finalizations will occur since obj still holds a reference. (4) See (3).

22 : 2 & 3 is correct.
Explanation:
(1) No, see (2). (2) Yes, the Math class has the max and min methods for integer and floating point primitives. (3) Yes, the String parsing methods are in the primitive wrapperclasses. (4) No, see (3).

23 : 1 is correct.
Explanation:
The line after the break statement would always be unreachable and thus the code would not compile.

24 : 3 is correct.
Explanation:
(1) The compiler does not object because the static final variable still points to the same object. Only if we had tried to assign another StringBuffer to the variable wouldthe compiler object. (2) & (4) see (3). (3) Yes, that is the contents of the variable after modification.

25 : 3 is correct.
Explanation:
(1) No, any array can be cast to an Object reference (2) No, because Object is the parent class of String, this is legal (3) This assignment causes an error because the type of aprimitive array can’t be changed to another primitive type by a cast (4) No, any array can be cast to an Object reference.

26 : 1,3 & 5 is correct.
Explanation:
The Set interface does not permit duplicate elements, but since ArrayList implements List and not Set, it can hold duplicates. Its methods are not synchronized, so it’s notthread-safe on its own. List classes use a ListIterator rather than a simple Iterator, because a ListIterator lets you traverse bi-directionally.It is well-suited for fast random access, and implements the RandomAccess interface. It also implements java.util.Collection (not Collections with an ‘s’).

27 : 2 is correct.
Explanation:
Math.abs returns the absolute of a number. Math.ceil returns the smallest double that is greater than or equal to the number, and also rounds it to the nearest integer.Math.floor returns the largest double that is less than or equal to the number, and rounds it to the nearest integer. Math.round returns the integer that is closest to the number,by adding .5 to the number and then truncating to get the nearest integer. Option “A” would be the correct answer if the System.out.println() statement had not includedthe “”, since that would cause the integer variables to be arithmetically added rather than concatenated as String values. (courtesy: Sun Microsystems)

28 : 3 is correct.
Explanation:
Resolves to (i * (j-1) ) + 1. (credit: Sun Microsystems)

29 : 6 is correct.
Explanation:
Option 6 is the correct answer. You can request that an object be destroyed, but only the GC decides when is actually destroyed. (courtesy: Sun Microsystems)

30 : 5 is correct.
Explanation:
Option 5 is the correct answer. The instance variable b is initialized to false, reset to false on line 8 and falls through to line 15, where x is set to 4.(courtesy: Sun Microsystems)

31 : 7 is correct.
Explanation:
Objects become eligible for garbage collection when all references to the object are removed from active threads. With the exception of a WeakHashMap a key stored in a Map isnot garbage collected when the references to the key are removed. A WeakHashMap can be used to avoid the memory leaks generally associate with the use of other implementations ofthe Map interface. (credit: danchisholm)

32 : 2 is correct.
Explanation:
Thread a1 intends to wait forever since no other thread invokes the notify method. After starting thread a1 the main method invokes the interrupt method on thread a1. Inresponse, thread a1 moves out of the Not-Runnable state. Once the thread begins to run it throws an InterruptedException and clears the interrupted flag. The exception is caught andthe interrupted method is invoked to test the state of the interrupted flag. Since the flag was cleared when the exception was thrown the return value of the interruptedmethod is false. (credit: danchisholm)

33 : 6 is correct.
Explanation:
Boolean class contains 2 instances of Boolean objs that are declared public static final Boolean.The 1st is Boolean.FALSE & wraps the primitive bool value false.The other is Boolean.TRUE and wraps the primitive boolean value true. Theequality operator ‘ll return true if the left & right operand are both Boolean.TRUE or if the left & right operand are both Boolean.FALSE. The same is true if the results of the Boolean.valueOf method are compared with the equality operator’cause the comparison is just a comparison of references to the constants Boolean.TRUE or Boolean.FALSE. Please note that Boolean.valueOf is generally preferable over the use of the Boolean constructor ’cause the Boolean.valueOf method does notcreate a new instance of a Boolean obj. The valueOf method is much faster than the use of the constructor & also saves memory. The use of the Boolean constructor is not recommended in any situation where the valueOf method is applicable.

34 : 4 is correct.
Explanation:
An anonymous class can extend another class or implement an interface. If the anonymous class extends another class then the class instance creation expression can include parameters. The parameters will be passed to a constructor ofthe super class. If the anonymous class implements an interface, then the instance creation expression can not include any parameters. An anonymous class can not be extended so it also can not be abstract. An anonymous classcan not be static. An anonymous class can not declare a constructor, but it can declare an instance initializer. (Credit: danchisholm)

35 : 2 is correct.
Explanation:
Though TechnoSuper is an abstract class, a TechnoSuper variable could correctly be initialized with a reference to any subclass of TechnoSuper that is not abstract. HereTechnoSub is not abstract and the statement (2) would be legal.

36 : 1 is correct.
Explanation:
This code implements an anonymous inner class that implements the Remote interface and will compile without error. Option 2 should be obvious nonsense as you cannot directly instantiate an interface (credit: www.examulator.com)

37 : 4 is correct.
Explanation:
The ~ operator flips all of the bits including the sign bit. Thus in this case you start off with 4 which in binary is
0000 0000 0000 0000 0000 0000 0000 0100
and after the ~ operation you end up with
1111 1111 1111 1111 1111 1111 1111 1011, which is binary representation of decima -5.Please read 2′s complement number encoding for negative value representation in Java.

38 : 2 is correct.
Explanation:
This code will produce a java.lang.IllegalMonitorStateException at runtime because the wait/notify code is not within synchronized code.(Credit: www.examulator.com)

39 : 2,3,4,5 & 6 is correct.
Explanation:
(Credit: www.examulator.com)

40 : 3 is correct.
Explanation:
It permits null values and null keys. It stores information as key/value pairs.This class does not guarantee the order of its elements over time.

41 : 1,3 & 4 is correct.
Explanation:
An interface can extend another interface but not a class. Interface methods are abstract by default. The purpose of interface methods are that they should be implemented in other classes, so there would not be much point in them beingfinal. (Credit: www.examulator.com)

42 : 2 is correct.
Explanation:
Having the same hashCode does not tell you that two objects are equal. If they are equal they must return the same HashCode value, but if they are not equal they could returnthe same hashCode value.

43 : 1 & 4 is correct.
Explanation:
An overriden method must have the same parameter types as in the parent class, but it does not need to have the same names for those parameters. An overriden method cannot throw exceptions not declared in the parent class version, but itcan throw fewer or no exceptions.

44 : 4 is correct.
Explanation:
If that seems a vauge answer it is because you cannot be certain of the system that the underlying OS uses for allocating cycles for a Thread. The chances are that once the thread has been spun off in the call to start in the methodpiggy the main method will run to completion and the value of sName will still be vandeluer before the Thread modifies it. You cannot be certain of this though.

Just because sName is static does not mean that passing it to a method gives the method the original copy. The method only sees a locally created copy and any changes to it will not be reflected on return to the calling method.

45 : 2 is correct.
Explanation:
(1) Fails to compile. As far as the compiler is concerned, obj is a plain Object so it objects to the assignment to a Runnable reference. (2) Compiles and runs. The compilerassumes you know what you are doing with the cast to Runnable. (3) Compiles but fails to run. Because of the specific cast, the compiler thinks you know what you are doing, but thetype of the base reference is checked when the statement executes and a ClassCastException is thrown. (4) Fails to compile. see (1). (Credit: www.lanw.com)

46 : 2 is correct.
Explanation:
(1) No – I is not a Long object, so the test fails. (2) Correct – the test results in a false value because I is not a Long object. All of the primitive wrapper object “equals”tests only compare content once they have determined that the input object is of the correct class. (3) & (4) No – because the signature of the equals method will take any object. (Credit: www.lanw.com)

47 : 2 is correct.
Explanation:
(1) No – the compiler will object because the public class name does not match the file name. (2) Right – the compiler error message is “public class Base must be defined in a filecalled Base.java”. Although it is common for a single Java source file to generate more than one class file on compilation, two public classes cannot occupy the same Java source file.(3) No – but if the source file had been named Base.java, then option (3) would be correct. (Credit: www.lanw.com)

48 : 1,2,3 & 4 is correct.
Explanation:
All of these changes would eliminate the warning. Both (1) & (2) provide for initializing the reference. (3) ensured that tmp gets initialized no matter what the value of n.(4) makes tmp a member variable which will be initialized to null.(Credit: www.lanw.com)

49 : \u03c0.
Explanation:
\u03c0 Or \u03C0. Unicode literals always starts with “\u” and have four hexadecimal digits. The hexadecimal digits can be either upper or lower case. (Credit: www.lanw.com)

50 : 1 is correct.
Explanation:
The scope of the “tmp” String is confined to the try block. (Credit: www.lanw.com)

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind

*

Close
Please support the site
By clicking any of these buttons you help our site to get better