Thursday, October 6, 2011

Questions with Explanations for OCPJP

Ques:
Given:
23. Object [] myObjects = {
24. new integer(12),
25. new String(”foo”),
26. new integer(5),
27. new Boolean(true)
28. };
29. Arrays.sort(myObjects);
30. for( int i=0; i<myObjects.length; i++) {
31. System.out.print(myObjects[i].toString());
32. System.out.print(” “);
33. }
What is the result?
A. Compilation fails due to an error in line 23.
B. Compilation fails due to an error in line 29.
C. A ClassCastException occurs in line 29.
D. A ClassCastException occurs in line 31.
E. The value of all four objects prints in natural order.
Answer: C
The format of the question is correct. But in arrays and
collections the elements inside the collection/array must be
mutually comparable. This will be known as an error only
during the runtime, because the complier does not know what
is inside the array until it runs

Ques:
10. interface Foo {}
11. class Alpha implements Foo { }
12. class Beta extends Alpha {}
13. class Delta extends Beta {
14. public static void main( String[] args) {
15. Beta x = new Beta();
16. // insert code here
17. }18. }
Which code, inserted at line 16, will cause a
java.lang.ClassCastException?
A. Alpha a = x;
B. Foo f= (Delta)x;
C. Foo f= (Alpha)x;
D. Beta b = (Beta)(Alpha)x;
Answer: B
When attempting to cast a reference variable to a type that
fails the IS-A test, a ClassCastException is Thrown.

Ques :
Given:
12. import java.io.*;
13. public class Forest implements Serializable {
14. private Tree tree = new Tree();
15. public static void main(String [] args) {
16. Forest f= new Forest();
17. try {
18. FileOutputStream fs = new FileOutputStream(”Forest.ser”);
19. ObjectOutputStream os = new ObjectOutputStream(fs);
20. os.writeObject(f); os.close();
21. } catch (Exception ex) { ex.printStackTrace(); }
22. } }
23.
24. class Tree { }
What is the result?
A. Compilation fails.
B. An exception is thrown at runtime.
C. An instance of Forest is serialized.
D. A instance of Forest and an instance of Tree are both serialized.

As per the Serialization rules the classes that are involving in serialization also should implement Serializable interface but here the class Tree is not implementing the Serializable interface, so it throws an Exception when it is trying to serialize the Forest class.


Ques:
 Assuming that the serializeBanana() and the deserializeBanana() methods will
correctly use Java serialization and given:
13. import java.io.*;
14. class Food implements Serializable {int good = 3;}
15. class Fruit extends Food {int juice = 5;}
16. public class Banana extends Fruit {
17. int yellow = 4;
18. public static void main(String [] args) {
19. Banana b = new Banana(); Banana b2 = new Banana();
20. b.serializeBanana(b); // assume correct serialization
21. b2 = b.deserializeBanana(); // assume correct
22. System.out.println("restore "+b2.yellow+ b2.juice+b2.good);
24. }
25. // more Banana methods go here 50. }
What is the result?

A. restore 400
B. restore 403
C. restore 453
D. Compilation fails.
E. An exception is thrown at runtime.
Answer: C
Since there is no problem in code and no complex flow, it is a general flow. So the corresponding values will be printed.


Ques:
21. public String toString() {
22. StringBuffer buffer = new StringBuffer();
23. buffer.append('<');
24. buffer.append(this.name);
25. buffer.append('>');
26. return buffer.toString();
27. }
Which statement is true?
A. This code is NOT thread-safe.
B. The programmer can replace StringBuffer with StringBuilder with no other changes.
C. This code will perform poorly. For better performance, the code should be rewritten:
return "<" + this.name + ">";
D. This code will perform well and converting the code to use StringBuilder will not enhance the performance.
Answer: B

Ques:
Given:
10. interface Foo { int bar(); }
11. public class Sprite {
12. public int fubar( Foo foo) { return foo.bar(); }
13. public void testFoo() {
14. fubar(
15. // insert code here
16.);
17. }
18. }
Which code, inserted at line
15, allows the class Sprite to compile?
A. Foo { public int bar() { return 1; } }
B. new Foo { public int bar() { return 1; } }
C. new Foo() { public int bar(){return 1; } }
D. new class Foo { public int bar() { return 1; } }
Answer: C
It is an Argument-Defined Anonymous Inner class.Option D is the wrong syntax because of class.Option A is wrong because a new keyword is not there.Option B is wrong because of the absence of the “()” after foo.


Ques :
Click the Exhibit button.
10. interface Foo {
11. int bar();
12. }
13.
14. public class Beta {
15.
16. class A implements Foo {
17. public int bar() { return 1; }
18. }
19.
20. public int fubar( Foo foo) { return foo.bar(); }
21.
22. public void testFoo() {
23.
24. class A implements Foo {
25. public int bar() { return 2; }
26. }
27.
28. System.out.println( fubar( new A()));
29. }
30.
31. public static void main( String[] argv) {
32. new Beta().testFoo();
33. }
34. }
Which three statements are true? (Choose three.)
A. Compilation fails.
B. The code compiles and the output is 2.
C. If lines 16, 17 and 18 were removed, compilation would fail.
D. If lines 24,
25 and 26 were removed, compilation would fail.
E. If lines 16, 17 and 18 were removed, the code would compile and
the output would be 2.
F. If lines 24, 25 and 26 were removed, the code would compile and
the output would be 1.
Answer: BEF
Read the question carefully cause it is tricky & perplex. Once new Beta.testfoo() is invoked, line number 28 System.out.println( fubar( new A())); is invoked.The invocation then calls the method fubar on line number 20.In fubar the foo.bar(); takes the version which was inside the testfoo() as it was overridden ie on the line 24,25,26(option B). If these 3 lines were deleted then the call goes to Beta version s bar() method on  line numbers 16,17,18 (Option E). Similarly for option F.

Ques:
Given:
1. package sun.scjp;
2. public enum Color { RED, GREEN, BLUE }
1. package sun.beta;
2. // insert code here
3. public class Beta {
4. Color g = GREEN;
5. public static void main( String[] argv)
6. { System.out.println( GREEN); }
7. }
The class Beta and the enum Color are in different packages.
Which two code fragments, inserted individually at line 2 of the Beta
declaration, will allow this code to compile? (Choose two.)
A. import sun.scjp.Color.*;
B. import static sun.scjp.Color.*;
C. import sun.scjp.Color; import static sun.scjp.Color.*;
D. import sun.scjp.*; import static sun.scjp.Color.*;
E. import sun.scjp.Color; import static sun.scjp.Color.GREEN;
Answer: CE
From the Code we know that for like 4 to work properly we a fully qualified name for sure. So in option E .Import static sun.scjp.Color.GREEN Tells us that this is the right option. Then out of the other options. We first need to import the package which must contain the enum, so we eliminate A because there is no static import. Remember static import is used for accessing static members. So here inside the enum all 3 colors are static.But we also need to access the color enum so we must have import sun.scjp.color.*; Option C is the right answer.

Ques:
Given:
1. class TestA {
2. public void start() { System.out.println(”TestA”); }
3. }
4. public class TestB extends TestA {
5. public void start() { System.out.println(”TestB”); }
6. public static void main(String[] args) {
7. ((TestA)new TestB()).start();
8. }
9. }
What is the result?
A. TestA
B. TestB
C. Compilation fails.
D. An exception is thrown at runtime.
Answer: B
Method to be called depends on the actual object type,not on the return type.Here new TestB() creates the object of TestB and this object is of return type TestA. But the object is still of TestB.

Ques:
Given:
11. public abstract class Shape {
12. int x;
13. int y;
14. public abstract void draw();
15. public void setAnchor(int x, int y) {
16. this.x = x;
17. this.y = y;
18. }
19. }
and a class Circle that extends and fully implements the Shape class. Which is correct?
A. Shape s = new Shape();
s.setAnchor(10,10);
s.draw();
B. Circle c = new Shape();
c.setAnchor(10,10);
c.draw();
C. Shape s = new Circle();
s.setAnchor(10,10);
s.draw();
D. Shape s = new Circle();
s->setAnchor(10,10);
s->draw();
E. Circle c = new Circle();
c.Shape.setAnchor(10,10);
c.Shape.draw();
Answer: C
Since we can not create an instance for abstract class options A and B are invalid. There is no operator such as -> in java so D is invalid, We cannot use both object and class for calling a method so E is invalid. Option C is the correct way to call the method of Circle by
creating a reference on the abstract class Shape.


Ques:
Click the Exhibit button.
1. public class GoTest {
2. public static void main(String[] args) {
3. Sente a = new Sente(); a.go();
4. Goban b = new Goban(); b.go();
5. Stone c = new Stone(); c.go();
6. }
7. }
8.
9. class Sente implements Go {
10. public void go() { System.out.println(”go in Sente.”); }
11. }
12.
13. class Goban extends Sente {
14. public void go() { System.out.println(”go in Goban”); }
15. }
16.
17. class Stone extends Goban implements Go { }
18.
19. interface Go { public void go(); }
What is the result?
A. go in Goban
go in Sente
go in Sente
B. go in Sente
go in Sente
go in Goban
C. go in Sente
go in Goban
go in Goban
D. go in Goban
go in Goban
go in Sente
E. Compilation fails because of an error in line 17.
Answer: C
When a.go(); is invoked go in sente is printed.
When b.go(); is invoked go in goban is printed.
So The output so far is
Go in sente
Go in goban
Only option C is there with this order. Then Go in Goban is printed.
Ques :
Given:
11. public static void parse(String str) {
12. try {
13. float f= Float.parseFloat(str);
14. } catch (NumberFormatException nfe) {
15. f= 0;
16. } finally {
17. System.out.println(f);
18. }
19. }
20. public static void main(String[] args) {
21. parse(”invalid”);
22. }
What is the result?
A. 0.0
B. Compilation fails.
C. A ParseException is thrown by the parse method at runtime.                                         D. A NumberFormatException is thrown by the parse method at runtime.
Answer: B
Since f is declared in try block its scope is in try block only it cannot be accessed from
out side of the try block i.e finally block also. So the compiler complains that the symbol f
cannot be resolved in line 17.

Ques :
Which two code fragments correctly create and initialize a static array
of int elements? (Choose two.)
A. static final int[] a = { 100,200 };
B. static final int[] a;
static { a=new int[2]; a[0]=100; a[1]=200; }
C. static final int[] a = new int[2] { 100,200 };
D. static final int[] a;
static void init() { a = new int[3]; a[0]=100; a[1]=200; }
Answer: AB
A is a simple way to create an static array (in C style). B is way which follows Java rules i.e, declaring, constructing and initializing.
option C looks like an Anonymous array, but its not.the int should not have a number  between the brackets []. If it was an Anonymous Array it should look like
static final int[] a;
a= new int[]{100,200};

Ques:
Given:
11. public class Ball {
12. public enum Color { RED, GREEN, BLUE };
13. public void foo() {
14. // insert code here
15. { System.out.println(c); }
16. }
17. }
Which code inserted at line 14 causes the foo method to print RED,
GREEN, and BLUE?
A. for( Color c : Color.values())
B. for( Color c = RED; c <= BLUE; c++)
C. for( Color c; c.hasNext() ; c.next())
D. for( Color c = Color[0]; c <= Color[2]; c++)                                        E. for( Color c = Color.RED; c <= Color.BLUE; c++)
Answer: A

Ques:
Given:
10. public class Fabric
11. public enum Color {
12. RED(0xff0000), GREEN(0x00ff00), BLUE(0x0000ff);
13. private final int rgb;
14. Color( int rgb) { this.rgb = rgb; }
15. public int getRGB() { return rgb; }
16. };
17. public static void main( String[] argv) {
18. // insert code here
19. }
20. }
Which two code fragments, inserted independently at line 18, allow the
Fabric class to compile? (Choose two.)
A. Color skyColor = BLUE;
B. Color treeColor = Color.GREEN;
C. Color purple = new Color( 0xff00ff);
D. if( RED.getRGB() < BLUE.getRGB() ) {}
E. Color purple = Color.BLUE + Color.RED;
F. if( Color.RED.ordinal() < Color.BLUE.ordinal() ) {}
Answer: BF
This is an example of a method,constructor inside an enum. The instance variable is private final int rgb; The constructor is Color( int rgb) { this.rgb = rgb; } The method is public int getRGB() { return rgb; }
In order  for the enum to work properly we need to make an enum instance. For that the proper syntax is Option B Color treeColor = Color.GREEN;
Option A is wrong because the syntax for the enum which is enumname.enumvalue
Option C is wrong because we cant add new values to the enum after its declaration.
Now for the 2nd pick Option D is wrong because of wrong syntax like option A
enumname.enumvalue .Option E is wrong again because purple cant be added or be
assigned as its invalid.
So option F is right.

Ques:
Given:
11. public enum Title {
12. MR(”Mr.”), MRS(”Mrs.”), MS(”Ms.”);
13. private final String title;
14. private Title(String t) { title = t; }
15. public String format(String last, String first) {
16. return title + “ “ + first + “ “ + last;
17. }
18. }
19. public static void main(String[] args) {
20. System.out.println(Title.MR.format(”Doe”, “John”));
21. }
What is the result?
A. Mr. John Doe
B. An exception is thrown at runtime.                                                                              C. Compilation fails because of an error in line 12.
D. Compilation fails because of an error in line 15.
E. Compilation fails because of an error in line 20.
Answer: A
As soon as line 20 has been invoked,the format uses the overridden method of the enum Title. But first the constructor runs and then the format method runs.

Ques:
Click the Exhibit button.
1. public class A {
2.
3. private int counter = 0;
4.
5. public static int getInstanceCount() {
6. return counter;
7. }
8.
9. public A() {
10. counter++;
11. }
12.
13. }
Given this code from Class B:
25.A a1 =new A();                                                                                                      26. A a2 =new A();
27. A a3 =new A();
28. System.out.printIn(A.getInstanceCount() );
What is the result?
A. Compilation of class A fails.
B. Line 28 prints the value 3 to System.out.
C. Line 28 prints the value 1 to System.out.
D. A runtime error occurs when line 25 executes.
E. Compilation fails because of an error on line 28.
Answer: A
Static Method should access the Static instance variables. So the code does not compile.
Since the static method getInstanceCount cannot reference the non static variable
counter the compiler fails to compile in line 6 saying that “A non static variables cannot
be referenced by static method”. So option A is correct.


Ques:
class C1{
static interface I
{static class C2
{  } }
public static void main(String a[])
{
C1.I.C2 ob1=new C1.I.C2();
System.out.println("object created");
} }

What is the result of attempting to compile and run the program?

1.prints object created
2.Compile time error
3.Runtime Excepion
4.None of the above
Answer: 1
Explanation:
A static interface or class can contain static members.Static members can be accessed without instantiating the particular class

Ques:
class C{
static int f1(int i) {
System.out.print(i + ",");
return 0;
}
public static void main (String[] args) {
int i = 0;
i = i++ + f1(i);
System.out.print(i);
}}
1.Prints: 0,0
2.Prints: 1,0
3.Prints: 0,1
4.Compile-time error
5.None of the above
Ans : 2

Ques :
class A extends Thread {
private int i;
public void run() {i = 1;}
public static void main(String[] args) {
A a = new A();
a.run();
System.out.print(a.i);
}}
Prints nothing
Prints: 1
Prints: 01
Compile-time error
None of the above
Explanation:a.run() method was called instead of a.start(); so the full program runs as a single thread so a.run() is guaranteed to complete Ans: 2

Ques :
Given:
11. public static void main(String[] args) {
12. String str = “null’;
13. if (str == null) {
14. System.out.println(”null”);
15. } else (str.length() == 0) {
16. System.out.println(”zero”);
17. } else {
18. System.out.println(”some”);
19. }  20. }
‘What is the result?
A. null
B. zero
C. some
D. Compilation fails.
E. An exception is thrown at runtime.
Answer: D
The format for if is if(---){ } elseif(---){}else{}
So compilation error.


MVC - MVP : Difference between these design patterns?

In traditional UI development - developer used to create a  View  using window or usercontrol or page and then write all logical code ...