805 OCPJP 6 Questions 788 SCJP 5 questions 650 OCPJWCD 5 questions 600 OCAJP 7 questions 610 OCPJP 7 questions 510 Upgrade to OCPJP 7 questions 900 Java J2EE Qns

Tutorials

OCPJP6 Free Mock Exam Practice Questions



Are you prepared for OCPJP6 1Z0-851 exam , check your mock score ?
OCPJP6 Practice Test 1Z0-851

Download android version

Questions
Question - 1


Given:
2. public class Test implements Runnable {
3.
4. public void run() {
5. System.out.println("run.");
6. throw new RuntimeException("Problem");
7. }
8. public static void main(String[] args) {
9. Thread t = new Thread(new Test());
10. t.start();
11. System.out.println("End of method.");
12. }
13.}
Which two can be results? (Choose two.)




A. End of method. java.lang.RuntimeException: Problem run.

B. End of method. run. java.lang.RuntimeException: Problem

C. java.lang.RuntimeException: Problem

D. End of method. java.lang.RuntimeException: Problem


A and B - correct answer.
output may be
End of method.
run.Exception in thread "Thread-0" 
java.lang.RuntimeException: Problem
	at Test.run(Test.java:12)
	at java.lang.Thread.run(Unknown Source)

or
End of method.
Exception in thread "Thread-0" java.lang.RuntimeException: Problem
	at Test.run(Test.java:12)
	at java.lang.Thread.run(Unknown Source)
run.



Question - 2


Which two statements are true? (Choose two.)


A. It is possible for more than two threads to deadlock at once.

B. If a piece of code is capable of deadlocking, you cannot eliminate the possibility of deadlocking by inserting invocations of Thread.yield().

C. It is possible for a single-threaded application to deadlock if synchronized blocks are used incorrectly.

D. Deadlocked threads release once their sleep() method's sleep duration has expired.


A and B - correct answer.
It is possible for more than two threads to deadlock at once.
If a piece of code is capable of deadlocking, you cannot eliminate the possibility of deadlocking by
inserting invocations of Thread.yield().



Question - 3


Given:
public class Test {
	
	 public static void main(String[] args) {
	 new Test().syncTest();
	 }
	 
	 void syncTest() {
		 Object obj = new Object();
		 synchronized (Thread.currentThread()) {
		 obj.wait();
		 obj.notify();
		 }
		 }
	}
Which two statements are true? (Choose two.)


A. This class would not compile with error message "Unhandled exception type IllegalMonitorStateException.".

B. This code can throw an InterruptedException.

C. This class would not compile with error message "Unhandled exception type InterruptedException"

D. This code can throw an IllegalMonitorStateException.


B and C - correct answer.
This class would not compile with error message "Unhandled exception type InterruptedException".



Question - 4


Given:
public class GotoGood extends Thread {
	 private int x = 2;
	 public static void main(String[] args) throws Exception {
	new GotoGood().makeItSo();
	 }
	 public GotoGood(){
		 System.out.println("test");
	 x = 5;
	 start();
	 }
	 public void makeItSo() throws Exception {
	 join();
	 x = x - 1;
	 System.out.println(x);
	 }
	 public void run() { 
		 System.out.println("run");
		 x *= 2; 
		 }
	}
What is the output?


A. test 4 run

B. test run 9

C. This class would not compile with error message "Unhandled exception type InterruptedException"

D. This code can throw an IllegalMonitorStateException.


B - correct answer.
Check join method,
The join() method waits for a thread to die. In other words, it causes the currently running threads to stop executing until the thread it joins with completes its task.




Question - 5


Given:
1.public class KoKo {
2.	synchronized void hoho(long n) {
3.		 for(int i = 1; i < 4; i++)
4.		 System.out.print(n + "-" + i + " ");
5.		 }
6.		 }

1.public class Test implements Runnable {
2.	 static KoKo pp2 = new KoKo();
3.	 public static void main(String[] args) {
4.	 new Thread(new Test()).start();
5.	 new Thread(new Test()).start();
6.	 }
7.	 public void run() { pp2.hoho(Thread.currentThread().getId()); }
8.	 }
What is the output?


A. 8-1 8-2 8-3 9-1 9-2 9-3

B. 8-1 9-2 10-3 8-1 9-2 10-3

C. 8-1 9-2 8-3 9-1 8-2 9-3

D. 9-1 8-2 8-3 10-1 9-2 8-3


B - correct answer.

The java.lang.Thread.getId() method returns the identifier of this Thread. The thread ID is a positive long number generated when this thread was created.



Question - 6


Which statements are true about Daemon Thread ?


A. It provides services to user threads for background supporting tasks. It has no role in life than to serve user threads.

B. There are many java daemon threads running automatically e.g. gc, finalizer etc.

C. Its life depends on user threads.It is a low priority thread.

D. JVM terminates the daemon thread if there is no user thread.


A, B, C and D - correct answer.

Daemon thread in java is a service provider thread that provides services to the user thread. Its life depend on the mercy of user threads i.e. when all the user threads dies, JVM terminates this thread automatically.



Question - 7


Given:
1.public class Test{
2.	 public static void main (String[] args) {
3.	 new Test().go();
4.	 }
5.	 public void go() {
6.	 Runnable r = new Runnable() {
7.	public void run() {
8.	 System.out.print("foo");
9.	 }
10.	 };
11.	 Thread t = new Thread(r);
12.	 t.start();
13.	 t.start();
14.	 }
15.	}
what is the result?


A. IllegalThreadStateException thrown at run time.

B. The code executes normally and prints "foo".

C. The code executes normally and prints nothing.

D. Compilation fails.


A - correct answer.

After staring a thread, it can never be started again. If you does so, an IllegalThreadStateException is thrown.
t.start() and then again t.start() causes IllegalThreadStateException.



Question - 8


Given:
1. public abstract class Base {
2. private int x;
3. private int y;
4. public abstract void method1();
5. public void setValues(int x, int y) {
6. this.x = x;
7. this.y = y;
8. }
9. }
Which two classes use the Base class correctly?


A. public abstract class Child extends Base { private int z; }

B. public class Child implements Base { private int z; }

C. public class Child extends Base { private int z; public void method1(); }

D. public class Child extends Base { private int z; public void method1() {/* code here */} }


A and D - correct answer.

abstract class can extend base abstract class without declaring abstract method in child abstract class.
Any child concrete class should implement the abstract method if it extends abstract class



Question - 9


Given:
1.public class Test {
2.	 public static void main(String[] args) {
3.	 new Test().printValue("good", 1);
4.	 new Test().printValue("good", "morning", 2);
5.	 }
6.	 public void printValue(String... y, int x) {
7.	 System.out.print(y[y.length - 1] + " ");
8.	 }
9.	 }
What is the result?


A. good morning

B. good good

C. good good morning

D. Compilation fails.


D - correct answer.

The variable argument type String of the method printValue must be the last parameter.



Question - 10


Given:
1.public class KoKo {
2.	public enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
3.	    THURSDAY, FRIDAY, SATURDAY }
4.		 }

1.public class EnumTest1 {
2.	 public static void main(String[] args) {
3.	// insert code here	 
4.	 }
5. }

Which code, inserted at line 14, allows the Sprite class to compile?


A. KoKo.Day d = Day.SATURDAY;

B. KoKo.Day d = TUESDAY;

C. KoKo.Day d = KoKo.Day.SATURDAY;

D. KoKo.Day d = KoKo.Day();


C - correct answer.

An enum type is a special data type that enables for a variable to be a set of predefined constants. 



Question - 11


Which statement is true about the classes in the exhibit?
1.public class Shape {
2.	public void draw(String points){};
3.}
1.public class Circle extends Shape {
2.	public void draw(String points){};
3.}
1.public class KoKo {
2.	public Shape doit() {
3.		return new Shape();
4.	}
5.	public String printValue() {
6.		return "Some Value";
7.	}
8.}
1.public class Test extends KoKo {
2.	public Circle doit(){
3.		 return new Circle();
4.		 }
5.		
6.		 public Object printValue() {
7.			 return "Some Value new";
8.		 }
9.}





A. Compilation of class Circle will fail because of an error in line 2.

B. Compilation of class Test will fail because of an error in line 2.

C. Compilation of class Test will fail because of an error in line 6.

D. Compilation will succeed for all classes.


C - correct answer.

If subclass override any method by changing the return type of super class method, then the return type of overriden method must be subtype of return type declared in original method inside the super class. This is the only way by which method can be overriden by changing its return type.
In this case "Object" is not subtype of "String".



Question - 12


Which statement is true about the classes and interfaces in the exhibit?

1.public interface A {
2.	public void draw(String points);
3.}
1.public class B implements A {
2.	public void draw(String points){};
3.}
1.public class KoKo {
2.	public A doit() {
3.		//more code here
4.	}
5.	public String printValue() {
6.		//more code here
7.	}
8.}
1.public class Test extends KoKo {
2.	public B doit(){
3.		 //more code here
4.		 }
5.		
6.		 private String printValue() {
7.			 //more code here
8.		 }
9.}





A. Compilation of class B will fail because of an error in line 2.

B. Compilation of class Test will fail because of an error in line 2.

C. Compilation of class Test will fail because of an error in line 6.

D. Compilation will succeed for all classes and interfaces.


C - correct answer.

If subclass override any method - Access specifier must not be more restrictive than original method(can be less restrictive).
Compilation of class Test will fail because of an error in line 6 , Access specifier is private.



Question - 13


What is the result?

1.public class Shape {
2.     String name = "No name";
3.    public Shape(String nm) { name = nm; }
4.}

1.public class Circle extends Shape {
2.	String cid = "0000";
3.	public Circle(String id) {
4.		cid = id;
5.		}
6.}

1.public class CircleTest{
2.	public static void main(String[] args){
3.		Circle e = new Circle("test");
4.		System.out.println(e.cid);
5.		}
6.}



A. Compilation of class Circle will fail because of an error in line 3.

B. test

C. Compilation of class CircleTest will fail because of an error in line 3.

D. Compilation will succeed for all classes and print "0000"


A - correct answer.

Implicit super constructor Shape() is undefined. Must explicitly invoke another constructor.



Question - 14


Given:

1.public class ColorTest{
2.	public enum MyColor {
3.		 RED(0xff0000), GREEN(0x00ff00), BLUE(0x0000ff);
4.		 private final int rgb;
5.		 MyColor(int rgb) { this.rgb = rgb; }
6.		 public int getRGB() { return rgb; }
7.		 };
8.		 
9.		 public static void main(String[] args) {
10.			 //insert code here			 
11.	   }
12.}

Which code fragment, inserted at line 10, allows the ColorTest class to compile?



A. MyColor homeColor = MyColor.GREEN;

B. MyColor homeColor = MyColor();

C. MyColor skyColor = BLUE;

D. MyColor homeColor = MyColor.GREEN();


A - correct answer.

MyColor homeColor = MyColor.GREEN; is correct.



Question - 15


Given:
1. public class GoodTest {
2. //insert code here
3. System.out.println("hi");
4. }
5. }

Which of the code fragments, inserted independently at line 2, compile?



A. public static void main(String...a) { public static void main(String... a) { public static void main(String[]... a) {

B. public static void main(String...a) { public static void main(String...[] a) {

C. public static void main(String...[] a){

D. Only public static void main(String...a) {


A - correct answer.

public static void main(String...a) {
public static void main(String... a) {
public static void main(String[]... a) {



Question - 16


Given:

public class Man {
	Man() { System.out.print("Man "); }
	  }
public class Father extends Man {
	Father(String type) { System.out.print(type); }
}
public class Son extends Father{
	Son() {
		 super("Father ");
		 new Father("Son ");
		}
    public static void main(String[] args){
    	new Son();
    }
}

What is the result?



A. Compilation fails.

B. Man Father Man Son

C. Man Father Man

D. Man Father Son


B - correct answer.

output is Man Father Man Son



Question - 17


Given:

1.public interface AInf {
2.	String toString();
3.}

1.public class B {
2.	public static void main(String[] args){
3.		System.out.println(new AInf() {
4.			public String toString() { return "success"; }
5.			});
6.	}
7.}

What is the result?



A. Compilation of class B will fail because of an error in line 3.

B. Compilation of class B will fail because of an error in line 4.

C. success

D. throws Exception


C - correct answer.

Annonymous inner class :
A class is created but its name is decided by the compiler which implements the AInf interface and provides the implementation of the toString() method.



Question - 18


Given:
1.public class Man {
2.	protected int age(int x) { return 0; }
3.}
4.
5.public class Father extends Man {
6.		// insert code here	
7.}
Which methods, inserted independently at line 6, will compile without error?


A. protected long age(int x,int y) { return 0; }

B. protected int age(int x) { return 0; }

C. public int age(int x) { return 0; }

D. protected long age(long x) { return 0; }


A, B, C and D - correct answer.

All are correct.
If subclass override any method - Access specifier must not be more restrictive than original method(can be less restrictive).



Question - 19


Given:
1.public class A {
2.	private int a;
3.	protected A(int a) { this.a = a; }
4.}
5.public class B extends A{
6.	public B(int a) { super(a); }
7.	public B() { this.a = 5; }
8.}
Which is inserted independently at line 7, will compile without error?


A. Change line 7 to - public B() { this(5); }

B. Change line 7 to - public B() { super(5); }

C. Change line 7 to - public B() { this(6); }

D. public B() { a = 5; }


A, B and C - correct answer.

With the current code,
Implicit super constructor A() is undefined. Must explicitly invoke another constructor.



Question - 20


Which John class properly represents the relationship "John has a best friend who is a Rat"?


A. class John { private Rat bestFriend; }

B. class John { private BestFriend Rat; }

C. class John { private Rat;

D. class John extends Rat { }


A - correct answer.

has-a relationship, which is also called object composition. In this case class John has composition object bestFriend of type Rat.



Question - 21


Given:
1. package com;
2. class Big {
3. public String name = "hello";
4. }
What can directly access and change the value of the variable name?


A. any class

B. any class in the com package

C. any class that extends Big

D. only the Big class


B - correct answer.

If you don't use any modifier, it is treated as default bydefault. The default modifier is accessible only within package.
In this case class Big has default access modifier.



Question - 22


Given:
1. abstract class Parent { public int age() { return 0; }
2. class Child extends Parent { public int age() { return 30; }
3. class FirstChild extends Child { public int age() { return 50; } ...
4. FirstChild firstc = new FirstChild();
5. Child child = new FirstChild();
6. Parent parent = new FirstChild();
7. System.out.println(firstc.age() + ", " + child.age() + ", " + parent.age());
What is the result?


A. 50 30 0

B. 50 50 50

C. 0 30 50

D. 0 0 0


B - correct answer.

Parent parent = new FirstChild(); or Child child = new FirstChild(); 

When Parent class reference variable refers to Child class object, it is known as Upcasting

. age() method is overriden , reference variable refer to child object, so called child class method.



Question - 23


Given:
1. abstract class Parent { public int age() { return 0; }
2. class Child extends Parent { public int age() { return 30; }
3. class FirstChild extends Child { public int age() { return 50; } ...
4. FirstChild firstc = new FirstChild();
5. Child child = new FirstChild();
6. Parent parent = new FirstChild();
7. FirstChild fchild = new Child();
8. FirstChild secondchild = (FirstChild)child;
9. System.out.println(firstc.age() + ", " + child.age() + ", " + parent.age());
What is the result?


A. If line 7 is removed, the compilation succeeds.

B. If line 8 is removed, the compilation succeeds.

C. 0 30 50

D. 0 0 0


A - correct answer.

Parent parent = new FirstChild(); or Child child = new FirstChild(); 

When Parent class reference variable refers to Child class object, it is known as Upcasting

. FirstChild fchild = new Child(); incompatible type.



Question - 24


Given:
1.public class Country {
2.	 private String country = "India";
3.	 public String getCountry() { return country; }
4.	 }
5.public class BigState extends Country {
6.	public String getCountry() { return super.country; }
7.}
8.public class SmallState extends Country{
9.	 public String getCountry(int x) { return super.getCountry(); }
10.	 public static void main(String[] args) {
11.	 System.out.print(new BigState().getCountry() + " " + new SmallState().getCountry());
12.	 }
13.}
What is the result?


A. If line 9 is removed, the compilation succeeds.

B. India

C. If line 6 is removed, the compilation succeeds.

D. If line 11 is removed, the compilation succeeds.


A - correct answer.

The field Country.country is not visible, because Country.country is private.If line no 6 is removed, the compilation succeeds.



Question - 25


Given:
1.public class Employee implements Serializable{  
2.		 String name;  
3.		 static String company="My Company";  
4.		 public Employee(String name) {  
5.		 this.name = name;  
6.		 }  
7.		}
8.public class Test{	
9.	public static void main(String[] args) throws Exception{
10.		Employee e = new Employee("John");
11.		  serializeObject(e);// assume serialize works fine		   
12.		  Employee e1=(Employee)deserializeObject(); // assume deserialize works fine
13.		  System.out.println(e1.name+" "+e1.company);		 	  
14.		 }
15.	}
What is the result?


A. John null

B. John My Company

C. Throws SerializationException.

D. If line 3 is removed, the compilation succeeds.


A - correct answer.

If there is any static data member in a class, it will not be serialized because static is the part of class not object.



Question - 26


Given:
1.public class Employee implements Serializable{  
2.		 String name="Bob";  
3.}
4.public class Teacher extends Employee{
5.	String school="MP";
6.}
7.public class Student extends Teacher{
8.	String classname="Ten";
9.	public static void main(String[] args) throws Exception{		
10.		Student s1 = new Student();
11.		serializeObject(s);// assume serialize works fine		   
12.		Student s1=(Student)deserializeObject(); // assume deserialize works fine
13.		System.out.println(s1.classname+" "+s1.school+ " "+s1.name);
14.		 }
15.}
What is the result?


A. Ten null null

B. Ten MP Bob

C. Compilation fails.

D. An exception is thrown at runtime.


B - correct answer.

Parent class properties are inherited to subclasses so if parent class is Serializable, subclass would also be.



Question - 27


Given:
1.public class DateTest{	
2.	public static void main(String[] args){		
3.		Date d = new Date(0L);
4.		String ds = "March 12, 2001";
5.		//insert code here
6.		try {
7.			d = df.parse(ds);
8.			System.out.println(d);
9.		} catch(ParseException e) { };
10.		 }
11.	}

Which of the code fragments, inserted independently at line 2, compile without error?



A. DateFormat df = new SimpleDateFormat("MMM dd, yyyy");

B. DateFormat df = new DateFormat("MMM dd, yyyy");

C. DateFormat df = new SimpleDateFormat("MON dd, yyyy");

D. DateFormat df = new DateFormat("MON dd, yyyy");


A and C - correct answer.

DateFormat is abstract class, cannot Instantiate.
DateFormat df = new SimpleDateFormat("MON dd, yyyy") would compile but throw runtime exception because "MON dd, yyyy" is correct date format.



Question - 28


Given:
1.public class NumberFormatTest{	
2.	public static void main(String[] args){	
3.		double input = 314159.27;
4.		NumberFormat nf = NumberFormat.getInstance(Locale.GERMAN);
5.		String b;
6.		//insert code here
7.		System.out.println(b);
8.	}
9.}
Which code, inserted at line 6, print the value of b to 2.356.798,23?


A. b = nf.parse( input );

B. b = nf.format( input );

C. b = nf.formatObject( input );

D. b = nf.parseObject( input );


B - correct answer.

format method of NumberFormat class format based on locale.



Question - 29


Given:
1.public class StrTest{	
2.	public static void main(String[] args){	
3.		String str = "120";
4.		str += 42;
5.		char[] charArray={'j','a','v','a'};
6.		String strArray=new String(charArray);
7.		 System.out.print(str +" "+strArray);
8.	}
9.}
What is the result?


A. 162 java

B. 12042 java

C. 162 j a v a

D. 12042 j a v a


B - correct answer.

In java, string is basically an object that represents sequence of char values.
An array of characters works same as java string.
str += 42 : 42 is appended to str object.



Question - 30


Given:
1.public class StrObjTest{	
2.	public static void main(String[] args){	
3.		String s1="Welcome";  
4.		String s2="Welcome";
5.		String s=new String("WelcomeNew");
6.	}
7.}
How many String objects created from the above code ?


A. 3

B. 2

C. 4

D. 5


A - correct answer.

String s1="Welcome";  
String s2="Welcome";//will not create new instance 
Firstly JVM will not find any string object with the value "Welcome" in string constant pool, so it will create a new object. After that it will find the string with the value "Welcome" in the pool, it will not create new object but will return the reference to the same instance.
String s=new String("Welcome");//creates two objects and one reference variable 
JVM will create a new string object in normal(non pool) heap memory and the literal "WelcomeNew" will be placed in the string constant pool. The variable s will refer to the object in heap(non pool).



Question - 31


Which capability exists only in java.io.FileWriter?


A. Writing a line separator to an open stream.

B. Writing to an open stream.

C. Flushing an open stream.

D. Closing an open stream.


A - correct answer.

Writing a line separator to an open stream.



Question - 32


Given:
1.public class FileTest{	
2.	public static void main(String[] args){	
3.		File dir = new File("dir");
4.		 dir.mkdir();
5.		File f1 = new File(dir, "f1.txt");
6.		try {
7.		 f1.createNewFile();
8.		 } catch (IOException e) { ; }
9.	}
10.}
The current directory does NOT contain a directory named "dir"
Which three are true? 



A. The file system has a directory named "dir", containing a file f1.txt.

B. Line 3 creates a directory named "dir" in the file system.

C. Line 4 creates a directory named "dir" in the file system.

D. Line 7 creates a directory named "dir" in the file system.


A and C - correct answer.

dir.mkdir() : create new directory in the file system.



Question - 33


Given:

1.public class ExpTest{	
2.	public static void main(String[] args){	
3.		try { testException(); }
4.		catch (RuntimeException ex) { System.out.print("runtime "); }
5.		System.out.print("end ");
6.	}
7.	static void testException() throws RuntimeException {
8.		try {
9.		System.out.print("testException ");
10.		throw new RuntimeException();
11.		}
12.		catch (Exception ex) { System.out.print("Exception "); }
13.		}
14.}
What is the result?



A. Compilation fails.

B. testException Exception runtime end

C. testException Exception end

D. testException runtime end


C - correct answer.

In the above example the testException() method throw an instance of RuntimeException, which is successfully handled using the catch statement. So testException() does not throw exception to main method.



Question - 34


Given:

1.public class A {
2.		protected Object returnSomeValue() throws IOException{
3.			return "somevalueA";
4.			}
5.}
6.class B extends A{
7.	public String returnSomeValue() throws Exception{
8.		return "somevalueB";
9.		}	
10.	public static void main(String[] args) throws Exception{
11.		B b = new B();
12.		System.out.println(b.returnSomeValue());
13.	}
14.}
What is the result?



A. somevalueB

B. somevalueA

C. Compilation of class B will fail because "The return type is incompatible with A.returnSomeValue()"

D. Compilation of class B will fail because "Exception Exception is not compatible with throws clause in A.returnSomeValue()"


D - correct answer.

Exception Exception is not compatible with throws clause in A.returnSomeValue().
If Super class method throws object of IOException class, then Subclass method can either throw same exception, or can throw no exception, but it can never throw object of Exception class (parent of IOException class).



Question - 35


Given:

1.public class A {
2.		protected Object returnSomeValue() throws IOException{
3.			return "somevalueA";
4.			}
5.}
6. class B extends A implements Comparable{
7.	public String returnSomeValue(){
8.		return "somevalueB";
9.		}
10.	//insert code here
11.	public static void main(String[] args) throws Exception{
12.		A b = new B();
13.		System.out.println(b.returnSomeValue());
14.	}
15. }
Which code, inserted at line 10, compile without error?



A. public int compareTo(A a){return 1;}

B. public int compareTo(B b){return 1;}

C. public int compareTo(Object o){return 1;}

D. public int compare(A a1,A a2){return 1;}


A - correct answer.

If any class implements Comparable interface then need to implement compareTo method.



Question - 36


Given:

1.public class TestStringBuilder {
2. private static StringBuilder builder;
3.
4.    public static void foo()
5.    {
6.        builder = new StringBuilder();
7.    }
8.
9.    public static void foo(final String a)
10.    {
11.        builder.append(a);
12.    }
13.
14.    public synchronized void bar(final String a)
15.    {
16.        builder.append(a);
17.    }
18.}
Which statements are true about TestStringBuilder?



A. line 6 is thread safe.

B. line 11 is thread safe.

C. line 16 is thread safe.

D. All methods of StringBuilder is synchronized.


A and C - correct answer.

The StringBuilder class is used	to create mutable (modifiable) string. The StringBuilder class is same as StringBuffer class except that it is non synchronize.



Question - 37


Given:

1.public class KOKO implements Serializable{
2.	public int i;
3.	public KOKO(int j){
4.		this.i=j;
5.		};		
6.	private void writeObject(ObjectOutputStream s)
7.		throws IOException{
8.		s.writeLong(i);
9.		 }
10.	
11.	private void readObject(ObjectInputStream s)
12.	 throws IOException {
13.		//insert code here
14.	 }
15.}
Which code, inserted at line 13, will allow this class to correctly serialize and deserialize?


A. i = s.readInt();

B. i = s.readLong();

C. i = s.readObject();

D. i = s.defaultReadObject();


A - correct answer.

s.readInt(); is correct, deserialize the int value. s.readLong();- Type mismatch: cannot convert from long to int.



Question - 38


Given:

1.public class SimpleDouble {
2.	public static void main(String[] args){
3.		double d = 456.6537;
4.		System.out.printf("|%7.2f| ", d);
5.		System.out.printf("|%5.2f| ", d);
6.	}
7.}
What is output?


A. | 456.65| |456.65|

B. | 456.65| |456.653|

C. |456.653| |456.65|

D. Compilation fails.


A - correct answer.

7.3 say "use 3 digits of precision".



Question - 39


Given:

1.public class TestApple {
2.	static boolean isSuccess=false;
3.	public static void main(String[] args){
4.		int i = 5;
5.		 boolean isTrue = true;		
6.		 if ((i == 3) && !isSuccess )
7.		 System.out.print("a ");
8.		 System.out.print("b ");
9.		 if ((isSuccess = true) && isTrue )
10.		 System.out.print("c ");		
11.	   if (isSuccess )
12.		 System.out.print("d ");
13.		 }
14.}
What is output?


A. c d

B. b c d

C. b

D. c


B - correct answer.

result is b c d.



Question - 40


Given:

1.interface A {}
2.interface B extends A {}
3.public class C implements B{}
4.public class D extends C{
5.	public static void main(String[] args){
6.		C c = new C();
7.		//insert code here
8.	}
9.}
Which code, inserted at line 7, will cause a java.lang.ClassCastException?


A. A a = (B)c;

B. A a = (D)c;

C. A a = c;

D. B b = c;


B - correct answer.

A a = (D)c;
java.lang.ClassCastException: C cannot be cast to D because class D is subclass of class C.




Question - 41


Given:

1.public class BioTest {
2.
3.	public static void main(String[] args){
4.		try {
5.			} catch (NullPointerException e1) {
6.			System.out.print("a");
7.			} catch (Exception e2) {
8.			System.out.print("b");
9.			} finally {
10.			System.out.print("c");
11.			}
12.	}
13.}
What is the result ?


A. Unreachable catch block for NullPointerException. This exception is never thrown from the try statement body

B. c

C. ac

D. bc


B - correct answer.

finally block execute every time irrespective of exception or not.




Question - 42


Given:

1.public class GeoM {
2.  	public static void main(String[] args){
3.		//some code here
4.		try {
5.		//some code here
6.			} catch (NullPointerException e1) {
7.		//some code here
8.			} catch (Exception e) {
9.	        //some code here
10.			} finally {
11.			System.out.print("finally");
12.			}
13.	}
14.}
Under which three circumstances will the code print "finally"? (Choose three.)


A. The code on line 3 throws an exception.

B. The code on line 5 throws an exception.

C. The code on line 7 throws an exception.

D. The code on line 9 throws an exception.


B, C and D - correct answer.

line number 3 is out of try block.
finally block execute every time irrespective of exception or not.




Question - 43


Given:
1.		int a = 3;
2.		int b = 10;
3.		do {
4.		a--;
5.		++b;
6.		} while (b < 6);
7.		System.out.print(a + "," + b);
What is result?


A. 2,10

B. 2,11

C. 3,9

D. 5,6


B - correct answer.

in this case do {}while() execute only once.




Question - 44


Given:
1.public class Test {    
2.	public static void main(String[] args){
3.		new Test().assertTest();
4.		}	
5.	private void assertTest(){
6.		boolean assertsOn;
7.		assert (assertsOn) : assertsOn = true;
8.		if(assertsOn) {
9.		System.out.println("assert is on");
10.		}
11.	}
12.}
What is result?


A. assert is on

B. Compile fails on line number 7

C. Compile fails on line number 8

D. Compile fails on line number 3


B and C - correct answer.

Compile fails on line number 7 and 8,
The local variable assertsOn may not have been initialized.



Question - 45


Given:


1.public class Guru3 {    
2.	public static void main(String[] args){
3.		A a = new A();
4.		a.methodA();
5.		}	
6.}
Which statement is true if a SearchException is thrown on line 3 of class B?

1.public class SearchException extends Exception{}

1.class A {
2.	public void methodA() {
3.		try {
4.		 B b = new B();
5.		 b.methodB();
6.		//more code here
7.		 } catch (SearchException se){
8.		 throw new NullPointerException();
9.		 }
10.		}
11.}
1.class B extends A {
2.	public void methodB() throws SearchException {
3.      //more code here
4.		}
5.	}
What is result?


A. Line 4 of class Guru3 must be called within a try block.

B. The exception thrown by methodB in class B is not required to be caught.

C. The exception thrown by methodA in class A is not required to be caught.

D. The method declared on line Line 4 of class Guru3 must be declared to throw a RuntimeException.


C - correct answer.

unchecked exceptions/runtime exceptions are not checked at compile-time rather they are checked at runtime.NullPointerException is runtime exception. Not required to catch.



Question - 46


Given:
1.public class PiTest {    
2.	public static void main(String[] args){
3.		Float pi = new Float(3.14f);
4.		Float pi1 = new Float(3.20f);
5.		if (pi > pi1) {
6.		System.out.print("pi is bigger than pi1. ");
7.		}
8.		else {
9.		System.out.print("pi is not bigger than pi1. ");
10.		}
11.		finally {
12.		System.out.println("Inside finally.");
13.		}
14.	}	
15.}
What is result?


A. Inside finally.

B. pi is not bigger than pi1. Inside finally.

C. Compilation fails.

D. An exception occurs at runtime.


C - correct answer.

Compilation fails on line number 11.
finally must be followed by try or catch block.



Question - 47


Given:
1.public class LargeTest {    
2.	Long a;
3.	long b;
4.	public LargeTest(long c) {
5.	 b = a+c;
6.	 System.out.println(b);
7.	 }
8.	 public static void main(String[] args) {
9.	new LargeTest(new Long(10L));
10.	 }
11.}
What is result?


A. 10

B. 100

C. A NullPointerException occurs at runtime.

D. A NumberFormatException occurs at runtime.


C - correct answer.

A NullPointerException occurs at runtime on line number 5, while unboxing Long object without value (treating as null).



Question - 48


Which statements are true about the hashCode and equals method?


A. When inserting an object into a hastable you use a key. The hash code of this key is calculated, and used to determine where to store the object internally.

B. If object1 and object2 have the same hash code, they do have to be equal too.

C. If object1 and object2 are equal according to their equals() method, they must also have the same hash code.

D. If object1 and object2 have the same hash code, they do NOT have to be equal too.


A, C and D - correct answer.

If object1 and object2 are equal according to their equals() method, they must also have the same hash code.
If object1 and object2 have the same hash code, they do NOT have to be equal too.



Question - 49


Given:
1.	  public void displayValues(List list) {
2.		  for ( Iterator itr = list.iterator(); itr.hasNext(); ) {
3.		  int i = ((Integer)itr.next()).intValue();
4.		 System.out.println(i);
5.		 }		 
6.		}
What three changes allow the class to be used with generics and avoid an unchecked warning?


A. Replace line 2 with "for (int i : list) {".

B. Remove line 3.

C. Replace the method declaration with "displayValues(List list)".

D. Replace line 2 with "for (Iterator itr : list) {".


A, B and C - correct answer.

With generics , we can declare "displayValues(List list)" and "for (int i : list) {" to avoid unnecessary type casting on line number 3.



Question - 50


Given:
1.public class StrBoo {
2.	public static void main(String[] args) {
3.		List lst = new ArrayList();
4.		lst.add(new Integer(12).intValue());
5.		lst.add(new String("foo"));
6.		lst.add(new Boolean(true));
7.		Arrays.sort(lst.toArray());
8.		for (int i = 0; i < lst.size(); i++) {
9.			System.out.print(lst.get(i).toString());
10.		}
11.	}
12.}
What is result?


A. 12 foo true

B. 12 foo TRUE

C. Compilation fails.

D. throws java.lang.ClassCastException


D - correct answer.

Arrays.sort :
Sorts the specified array of objects into ascending order, according to the natural ordering of its elements. All elements in the array must implement the Comparable interface. Furthermore, all elements in the array must be mutually comparable (that is, e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the array).



Question - 51


Given:
EventGoGo.java
1.package gogo;
pu2.blic class EventGoGo {
3.	public static String goodMoring(String s) { return "Good Morning "+s; }
4.}
Test.java
1.
2.public class Test {
3.	public static void main(String[] args) {
4.		out.println(goodMoring("John"));
5.		
6.	}
7.}
Which code should be inserted at line 1 of Test.java to compile and run Test to print "Good Morning John"?


A. import static java.lang.System.*; import static gogo.EventGoGo.goodMoring;

B. import static gogo.EventGoGo.goodMoring;

C. static import java.lang.System.*; static import gogo.EventGoGo.goodMoring;

D. Compilation fails on line number 4 in Test.java.


A - correct answer.

Less coding is required if you have access any static member of a class oftenly.
You can access directly static methods using static imports.



Question - 52



A UNIX user named John run a Java drawShape program starting from his home directory /
home/john using the command:

java -classpath /android:/home/john/downloads/*.jar games.drawShape

John's CLASSPATH is set to:
/usr/lib:/home/john/classes:/opt/java/lib:/opt/java/lib/*.jar

What is a possible location for the drawShape.class file?



A. /android/games/drawShape.class

B. /home/john/drawShape.class

C. /home/android/games/drawShape.class

D. /home/games/drawShape.class


A - correct answer.

John is running program using below command , that means class file is in android folder and package name is games.
java -classpath /android:/home/john/downloads/*.jar games.drawShape



Question - 53



1. package com.android.games;
2. public class drawShape {
3. public static void main(String[] args) {}
4. }
And drawShape exists in the /code/com/android/games directory. Assume the CLASSPATH
environment variable is set to "." .Which two java commands entered at the command
line will run drawShape? (Choose two.)



A. java -classpath /code com.android.games.drawShape if run from any directory.

B. java com.android.games.drawShape if run from the /code directory.

C. java -classpath /code/com/android/games/drawShape if run from any directory.

D. java drawShape if run from the /code directory.


A - correct answer.

java -classpath /code com.android.games.drawShape if run from any directory.
that means class file is in android code and package name is com.android.games.




Question - 54



Which statement is true about finalize() method ?



A. finalize() is called before Garbage collector reclaim the Object.

B. finalize() method gets called only once by GC threads for a given object.

C. finalize() method is defined in java.lang.Object class, therefore it is available to all the classes.

D. finalize() method gets called may times by GC threads for a given object.


A, B and C - correct answer.

finalize() is called before Garbage collector reclaim the Object.
finalize() method gets called only once by GC threads for a given object.
finalize() method is defined in java.lang.Object class, therefore it is available to all the classes.




Question - 55



1.import static java.lang.System.*;
2.public class ClassHasPrivateMethod {
3.  private void privateMethod(){
4.	  out.println("I am private");
5.  }
6.}
1.public class Test {
2.	public static void main(String[] args) throws Exception{
3.	ClassHasPrivateMethod d = new ClassHasPrivateMethod();
4.      Method m = ClassHasPrivateMethod.class.getDeclaredMethod("privateMethod");
5.        m.setAccessible(true); 
6.      m.invoke(d);		
7.	}
8.}
What is result?


A. I am private.

B. private method cannot be accessed for outside.

C. Compilation fails on line number 4 of ClassHasPrivateMethod class.

D. Compilation fails on line number 4 of Test class.


A - correct answer.

You can access private method of a class from outside using reflection. 




Question - 56



1.public class Employee {  
2.	    String empName;
3.		public Employee(String name){
4.			empName = name;
5.		}
6.		public void printMessage(){
7.			System.out.println(empName);
8.		}
9.	}
10.public class Test {
11.	public static void main(String[] args) throws Exception{
12.    Class classToLoad = Employee.class;
13.        Class[] cArg = new Class[1];
14.        cArg[0]=String.class;
15.        Employee e=(Employee)classToLoad.getDeclaredConstructor(cArg).newInstance("Bob");
16.        e.printMessage();		
17.	}	
18.}
What is result?


A. Bob

B. RunTime Exception.

C. Compilation fails on line number 15.

D. Compilation fails on line number 16.


A - correct answer.

This is the way to call parameterized newInstance method.




Question - 57



public class NumTest {
	int squares = 21;
	 public static void main(String[] args) {
	 new Test().go();
	 }
	 void go() {
	 incr(++squares);
	 incr(++squares);
	 System.out.println(squares);
	 }
	 void incr(int squares) { squares += 10; }
}
What is result?


A. 23

B. 43

C. 32

D. 42


A - correct answer.

Correct answer is 23, int squares is passed by value.
void incr(int squares) { squares += 10; }//changes will be in the local variable only .




Question - 58



What is the output for the below code ?

1. public class Test {			
2.	public static void main(String... args) {
3.		int x =5;
4.		x *= 3 + 7;
5.		System.out.println(x);
6.	}
7. }



A. 22

B. 50

C. 10

D. Compilation fails with an error at line 4


B - correct answer.

x *= 3 + 7; is same as x = x * (3 +7) = 5 * (10) = 50 because expression on the right is always placed inside parentheses.




Question - 59



What is the output for the below code ?

public class A {
   public void printValue(){
	   System.out.println("A");
   }
}

public class B extends A {
	public void printValue(){
		   System.out.println("B");
	   }
}

public class C extends A{
	public void printValue(){
		   System.out.println("C");
	   }
}

1. public class Test {		
2.	public static void main(String... args) {
3.		A b = new B();
4.		A c = new C();
5.		System.out.println(b instanceof A);
6.		System.out.println(b instanceof C);
7.	}
8. }



A. true true

B. true false

C. false false

D. Compilation fails with an error at line 5 and 6


B - correct answer.

instanceof operator is used for object reference variables to check whether an object is of a particular type. reference variable b is a type of A BUT b is not type C.




Question - 60



What is the output for the below code ?

public  class A {
	
	public A(int i){
		System.out.println(i);
	}	
		
}

1. public class B extends A{		
2.	public B(){
3.		super(6);
4.		this();
5.	}	
6. }

public class Test{	
	public static void main (String[] args){
		B b = new B();		
	}
}




A. 6

B. 0

C. Compilation fails due to an error on lines 3

D. Compilation fails due to an error on lines 4


D - correct answer.

A constructor can NOT have both super() and this(). Because each of those calls must be the first statement in a constructor, you can NOT use both in the same constructor.




Ads
Are you prepared for OCPJP6 1Z0-851 exam , check your mock score ?
scjp 1.5 | scjp 1.6 | scwcd 1.5
Java Certifications
www.javacertifications.net