OCPJP 6 Mock Exam -11

1 . Consider following classes:

//In File Other.java
package other;
public class Other
{
    public static String hello = "Hello";
}

//In File Test.java
package testPackage;
import other.*;
class Test
{
   public static void main(String[] args)
   {
      String hello = "Hello", lo = "lo";
      System.out.print((testPackage.Other.hello == hello) + " ");    //line 1
      System.out.print((other.Other.hello == hello) + " ");   //line 2
      System.out.print((hello == ("Hel"+"lo")) + " ");    //line 3
      System.out.print((hello == ("Hel"+lo)) + " ");  //line 4
      System.out.println(hello == ("Hel"+lo).intern());  //line 5
   }
}

class Other
{
    static String hello = "Hello";
}

What will be the output of running class Test?

  1. false false true false true
  2. false true true false true
  3. true true true true true
  4. true true true false true
  5. None of the above

2 . Any class may be unloaded when none of it’s instances and class objects that represent this class are reachable. True Or False?

  1. True
  2. False

3 . The following program will print java.lang.ArithmeticException: / by zero.?

class Test
{
   public static void main(String[] args)
   {
      int d = 0;
      try
      {
         int i = 1 / (d* doIt());
      } catch (Exception e)
      {
         System.out.println(e);
      }
   }

   public static int doIt() throws Exception
   {
      throw new Exception("Forget It");
   }
}

True Or False?
Choose the one below:

  1. True
  2. False

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

public class TestClass
{
   public static void main(String args[ ] )
   {
      A o1 = new C( );
      B o2 = (B) o1;
      System.out.println(o1.m1( ) );
      System.out.println(o2.i );
   }
}

class A
{
    int i = 10;
    int m1( ) {
        return i;
    }
}

class B extends A
{
    int i = 20;
    int m1() {
        return i;
    }
}

class C extends B {
    int i = 30;
    int m1() {
        return i;
    }
}

Choose the one below:

  1. The progarm will fail to compile
  2. Class cast exception at runtime
  3. It will print 30, 20
  4. It will print 30, 30
  5. It will print 20, 20

5 . The following code snippet will print true.?

String str1 = "one";
String str2 = "two";
System.out.println( str1.equals(str1=str2) );

Choose the one below:

  1. True
  2. False

6 . Which of the following statements are true?

  1. An anonymous class cannot be inherited
  2. An anonymous class may extend another class
  3. An anonymous class may not create and start a Thread
  4. An anoymous class may not declare a constructor

7 . What will be the output?

class TestClass
{
   int i;
   public TestClass(int i) { this.i = i;  }
   public String toString()
   {
       if(i == 0) return null;
       else return ""+i;
   }

   public static void main(String[ ] args)
   {
      TestClass t1 = new TestClass(0);
      TestClass t2 = new TestClass(2);
      System.out.println(t2);
      System.out.println(""+t1);
   }
}

Choose the one below:

  1. It will throw NullPointerException when run
  2. It will not compile
  3. It will print 2 and then will throw NullPointerException
  4. It will print 2 and null
  5. None of the above

8 . Which of the following statements about NaNs are true ?

  1. Float.NaN == Float.NaN
  2. Float.NaN == Double.NaN
  3. Float.NaN >= 0
  4. Float.NaN < 0
  5. None of the above

9 . What will be the output?

boolean b1 = false;
boolean b2 = false;
if (b2 != b1 = !b2)
{
   System.out.println("true");
}
else
{
   System.out.println("false");
}

Choose the one below:

  1. Compile time error
  2. It will print true
  3. It will print false
  4. Runtime error
  5. It will print nothing

10 . Given two collection objects referenced by c1 and c2, which of these statements are true?

  1. c1.retainAll(c2) will not modify c1
  2. c1.removeAll(c2) will not modify c1
  3. c1.addAll(c2) will return a new collection object, containing elements from both c1 and c2
  4. For: c2.retainAll(c1); c1.containsAll(c2); 2nd statement will return true
  5. For: c2.addAll(c1); c1.retainAll(c2); 2nd statement will have no practical effect on c1

11 . What will be the output?

class TechnoSample {
    public static void main(String[] args) {
        double d1 = 1.0;
        double d2 = 0.0;
        byte b =1;

        d1 = d1/d2;
        b = (byte) d1;
        System.out.print(b);
    }
}

Choose the one below:

  1. It results in the throwing of an ArithmeticExcepiton
  2. It results in the throwing of a DivedeByZeroException
  3. It displays the value 1.5
  4. It displays the value –1

12 . Class finalization can be done by implementing the following method:

static void classFinalize() throws Throwable;

True Or False?

Choose the one below:

  1. True
  2. False

13 . Consider the following method:

public void getLocks(Object a, Object b)
{
  synchronized(a)
  {
    synchronized(b)
    {
      //do something
    }
  }
}

and the following instantiations:

Object obj1 = new Object();
Object obj2 = new Object();

obj1 and obj2 are accesible to two different threads and the threads are about to call the getLocks() method.
Assume the first thread calls the method getLocks(obj1, obj2).

Which of the following is true?

  1. The second thread should call getLocks(obj2, obj1)
  2. The second thread should call getLocks(obj1, obj2)
  3. The second thread should call getLocks() only after first thread exits out of it
  4. The second thread may call getLocks() any time and passing parameters in any order
  5. None of the above

14 . Which of these statements concerning nested classes and interfaces are true?

  1. An instance of a top-level nested class has an inherent outer instance
  2. A top-level nested class can contain non-static member variables
  3. A top-level nested interface can contain static member variables
  4. A top-level nested interface has an inherent outer instance associated with it
  5. For each instance of the outer class, there can exist many instances of a non-static inner class

15 . Given the following definition of class, which member variables are accessible from OUTSIDE the package com.technopark?

package com.technopark;

public class TestClass
{
   int i;
   public int j;
   protected int k;
   private int l;
}

Choose the one below:

  1. Member variable i
  2. Member variable j
  3. Member variable k
  4. Member variable k, but only for subclasses
  5. Member variable l

16 . Which of the following are wrapper classes for primitive types?

  1. java.lang.String
  2. java.lang.Void
  3. java.lang.Null
  4. java.lang.Object
  5. None of the above

17 . Which of the following statements are true?

  1. Private methods cannot be overriden in subclasses
  2. A subclass can override any method in a non-final superclass
  3. An overriding method can declare that it throws a wider spectrum of exceptions than the method it is overriding
  4. The parameter list of an overriding method must be a subset of the parameter list of the method that it is overriding
  5. The over riding method may opt not to declare any throws clause even if the original method has a throws clause

18 . Will the following code compile ? If yes , what will be the output ?

class sample {

		sample(int i){
			System.out.println(i);
			this.i = i;

		}

		public static void main(String args[]){
			sample object = new sample(10);
		}
}

Choose the one below:

  1. 0
  2. 10
  3. null
  4. Compile error “sample.java:10: No variable i defined in class sample”

Answers

1 : 4 is correct.
Explanation:
These are the six facts:
1. Literal strings within the same class in the same package represent references to the same String object.

2. Literal strings within different classes in the same package represent references tothe same String object. (So line 1 prints true)

3. Literal strings within different classes in different packages represent references to the same String object. (So line 2 prints true)

4. Strings computed by constantexpressions are computed at compile time and then treated as if they were literals. (So line 3 prints true)

5. Strings computed at run time are newly created and therefore are distinct. (So line 4 prints false)

6. The resultof explicitly interning a computed string is the same string as any pre-existing literal string with the same contents. (So line 5 prints true) (credit: www.jdiscuss.com)

2 : 2 is correct.
Explanation:
A class or interface may be unloaded if and only if its class loader is unreachable (the definition of unreachable is given in JLS 12.6.1). Classes loaded by the bootstrap loader are not unloaded. (credit: www.jdiscuss.com)

3 : 2 is correct.
Explanation:
It will print “Forget It” because before the division could take place doIt() throws an exception.

Java guarantees that every operand of an operator (except the conditional operators &&, ||, and ? :) appears to be fully evaluatedbefore any part of the operation itself is performed. If the binary operator is an integer division / or integer remainder % , then its execution may raise an ArithmeticException, but this exception is thrown only afterboth operands of the binary operator have been evaluated and only if these evaluations completed normally. (credit: www.jdiscuss.com)

4 : 3 is correct.
Explanation:
Remember : variables are shadowed and methods are overridden. Which variable will be used depends on the class that the variable is declared of. Which method will be used depends on the actual class of the object that is referenced by thevariable. So, in line o1.m1(), the actual class of the object is C, so C’s m1() will be used. So it retruns 30. In line o2.i, o2 is declared to be of class B, so B’s i is used. So it returns 20. (credit: www.jdiscuss.com)

5 : 2 is correct.
Explanation:
First the value of str1 is evaluated (ie. one). Now, before the method is called the operands are evaluated, so str1 becomes “two”. so “one”.equals(“two”) is false.

6 : 1,2 & 4 is correct.
Explanation:
As an anonymous class has no name another class would have nothing to put after the extends keyword. A constructor is a method with the same name as the class and no return type. If the class has no name there is no name to give a constructormethod. (credit: www.examulator.com)

7 : 4 is correct.
Explanation:
The method print() if OutputStream takes an Object and prints out a string that is returned by calling toString() on that object. Note that as toString() is defined in Object class, all objects in java have this method. So it prints 2 first.

The second object’s toString() returns null, so it prints “null”. There is no NullPointerException because no method is called on null.

Now, the other feature of print/println methods is that if they get null as input parameter, they print “null”. They do not try to call toString() on null. So, if you have, Object o = null; System.out.println(o); will print null and will not throw NullPointerException.

8 : 5 is correct.
Explanation:
NaN is unordered, so a numeric comparison operation involving one or two NaNs always returns false and any != comparison involving NaN returns true, including x != x when x is NaN.

9 : 1 is correct.
Explanation:
Note that, boolean operators have more precedence than =. (In fact, = has least precedenace) so, in (b2 != b1 = !b2) first b2 != b1 is evaluated which returns a value ‘false’. So the expression becomes false = !b2. And this is illegalbecause false is a value and not a variable!

Had it been something like (b2 = b1 != b2) then its valid because it will boil down to : b2 = false. Because all an if() needs is a boolean, now b1 != b2 returns false which is a boolean andas b2 = false is an expression and every expression has a return value (which is actually the LHS of the erpression). Here it returns true which is again a boolean.

Note, return value of expression (i is int) : i = 10 , is 10 (anint).

10 : 4 & 5 is correct.
Explanation:
public boolean retainAll(Collection c) retains only the elts in this collection that are contained in the specified collection. In other words, removes from this collection all of its elts that are not contained in the specified collection

public boolean removeAll(Collection c) removes all this collection’s elts that are also contained in the specified collection. After this call returns, this collection will contain no elts in common with the specifiedcollection

public boolean containsAll(Collection c) returns true if this collection contains all of the elts in the specified collection

public boolean addAll(Collection c) adds all the elts in the specified collectionto this collection. The behavior of this opern is undefined if the specified collection is modified while the opern is in progress(ie., the behavior of this call is undefined if the specified collection is this collection, and is nonempty)

11 : 4 is correct.
Explanation:
1.0/0.0 results in Double.POSITIVE_INFINITY. Double.POSITIVE_INFINITY is converted to Integer.MAX_VALUE (’0′ followed by 31 ’1′s). Integer.MAX_VALUE is then cast to byte value, which simply takes the last 8 bits(11111111) and is -1.

12 : 2 is correct.
Explanation:
PREVIOUSLY: If a class declares a class method classFinalize that takes no arguments and returns no result: static void classFinalize() throws Throwable { . . . } then this method will be invoked before the class is unloaded . Like thefinalize method for objects, this method will be automatically invoked only once. This method may optionally be declared private, protected, or public.

NOW: Class finalization has been removed from the Java language. Thefunctionality of JLS 12.7 is subsumed by instance finalization (JLS 12.6).Here is a rationale for this decision. http://java.sun.com/docs/books/jls/class-finalization-rationale.html
Similar thing has happend toclass unloading: A class or interface may be unloaded if and only if its class loader is unreachable (the definition of unreachable is given in JLS 12.6.1). Classes loaded by the bootstrap loader may not be unloaded.

13 : 2 is correct.
Explanation:
(1) This may result in a deadlock (3) The is not necessary. Option 2 works just fine

14 : 2,3 & 5 is correct.
Explanation:
Inner class means a NON STATIC class defined inside a class. Top level nested class means a STATIC class defined inside a class.

One can define a class as a static member of any top-level class. Classes which are static class members andclasses which are package members are both called top-level classes. They differ from inner classes in a sense that a top-level class can make direct use only of its own instance variables. The ability to nest classes in this way allows anytop-level class to provide a package-like organization for a logically related group of secondary top-level classes, all of which share full access to private members.(credit: www.jdiscuss.com)

15 : 2 & 4 is correct.
Explanation:
public > protected > package (ie. no modifier) > private where public is least restrictive

Remember:
protected is less restrictive than package access. So a method(or field) declared as protected will be accessible from asubclass even if the subclass is not in the same package. The same is not true for package access.

A class can only have either public or no access modifier but a method or field can have all the four. Note that static, final, nativeand synchronized are not considered as access modifiers

16 : 5 is correct.
Explanation:
Frequently it is necessary to represent a value of primitive type as if it were an object. There are following wrapper classes for this purpose: Boolean, Byte, Character, Short, Integer, Long, Float, and Double.

Note that Byte,Short, Integer, Long, Float and Double extend from Number which is an abstract class. An object of type Double, for example, contains a field whose type is double, representing that value in such a way that a reference to it can be storedin a variable of reference type. These classes also provide a number of methods for converting among primitive values, as well as supporting such standard methods as equals and hashCode

17 : 1 & 5 is correct.
Explanation:
A method can be overriden by defining a method with the same signature(i.e. name and parameter list) and return type as the method in a superclass. Only methods that are accessible can be overriden. A private method cannot therefore beoverriden in subclasses, but the subclasses are allowed to define a new method with exactly the same signature. A final method cannot be overriden. An overriding method cannot exhibit behaviour that contradicts the declaration of theoriginal method. An overriding method therefore cannot return a different type or throw a wider spectrum of exceptions than the original method in the superclass

18 : 4 is correct.
Explanation:
(source: http://www.geocities.com/gnashes30/java/quest_bank/qb1.htm)

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

*