0% found this document useful (0 votes)
183 views28 pages

Very Tough Test 9

The document contains explanations for 8 code snippets. The first code snippet prints 5, as i is incremented multiple times within the if statement to the value of 5. The second code snippet prints C and E, as C is printed when i is 2, and E is printed when i is 4 as it falls through multiple switch cases. The third code snippet converts the string "123" to a long by using Long.parseLong(mStr) or new Long(mStr) or Long.valueOf(mStr).longValue(). The remaining code snippets are summarized in 1-2 sentences explaining the output or reason for (non)compilation.

Uploaded by

suhas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
183 views28 pages

Very Tough Test 9

The document contains explanations for 8 code snippets. The first code snippet prints 5, as i is incremented multiple times within the if statement to the value of 5. The second code snippet prints C and E, as C is printed when i is 2, and E is printed when i is 4 as it falls through multiple switch cases. The third code snippet converts the string "123" to a long by using Long.parseLong(mStr) or new Long(mStr) or Long.valueOf(mStr).longValue(). The remaining code snippets are summarized in 1-2 sentences explaining the output or reason for (non)compilation.

Uploaded by

suhas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

1) What will the following code print?

int i = 1;

int j = i++;
if( (i==++j) | (i++ == j) ){
i+=j;
}
System.out.println(i);

You had to select 1 option


a) 3
b) 4
c) 5
d) 2
e) It will not compile.

Choose the correct Answer:C

Explanation: This question is based on 2 concepts:

1. i == ++j is not same as i == j++;


In the case of i == ++j, j is first incremented and then compared with i. While in the case of i
== j++;, j is first compared with i and then incremented.

2. The | operator, when applied for boolean operands, ensures that both the sides are evaluated.
This is opposed to || which does not evaluate the Right Hand Side if the result can be known by
just evaluating the Left Hand Side.

Now, let us see the values of i and j at each step:

int i = 1;
int j = i++; // j is assigned 1 and i is incremented to 2
if( (i==++j) | (i++ == j) ) // increment j (so j becomes 2)
and compare with i => return true.
//since it is |, evaluate next condition: compare i with
2 and increment i => i becomes 3.{
i+=j; //i = 3+2 = 5
}
System.out.println(i); //prints 5
2) What letters will be printed by this program?

public class ForSwitch{

public static void main(String args[]){

char i;

LOOP: for (i=0;i<5;i++){

switch(i++){

case '0': System.out.println("A");

case 1: System.out.println("B"); break LOOP;

case 2: System.out.println("C"); break;

case 3: System.out.println("D"); break;

case 4: System.out.println("E");

case 'E' : System.out.println("F");

You had to select 2 options

a) A
b) B
c) C
d) D
e) F

Choose the correct Answer:C,E

Explanation: 1. Defining i as char doesn't mean that it can only hold characters (a, b, c etc). It is an
integral data type which can take any +ive integer value from 0 to 2^16 -1.

2. Integer 0 or 1, 2 etc. is not same as char '0', '1' or '2' etc.

so when i is equal to 0, nothing gets printed and i is incremented to 1 (due to i++ in the switch).
i is then incremented again by the for loop for next iteration. so i becomes 2.

when i = 2, "C" is printed and i is incremented to 3 (due to i++ in the switch) and then i is
incremented to 4 by the for loop so i becomes 4.

when i = 4, "E" is printed and since there is no break, it falls through to case 'E' and "F" is printed.

i is incremented to 5 (due to i++ in the switch) and then it is again incremented to 6 by the for loop.
Since i < 5 is now false, the for loop ends.

2) Given:
String mStr = "123";
long m = // 1 Which of the following options when put at //1 will assign 123 to m?

You had to select 3 options


a) new Long(mStr);
b) Long.parseLong(mStr);
c) Long.longValue(mStr);
d) (new Long()).parseLong(mStr);
e) Long.valueOf(mStr).longValue();

Choose the correct Answer: A,B,E

4) Given:

public class TestClass{

public static int getSwitch(String str){

return (int) Math.round( Double.parseDouble(str.substring(1, str.length()-1)) );

public static void main(String args []){

switch(getSwitch(args[0])){

case 0 : System.out.print("Hello ");

case 1 : System.out.print("World"); break;

default : System.out.print("Good Bye");

}
}

What will be printed by the above code if it is run with command line: java TestClass --0.50 (There are
two minuses before 0.)

You had to select 1 option

a) Hello
b) World
c) Hello World
d) Hello World Good Bye
e) Good Bye

Choose the correct Answer:C

Explanation: str.substring(1, str.length()-1) => "--0.50".substring(1,


(6-1) ) => -0.5
Math.round(-0.5) = 0.0
so getSwitch(...) returns 0 if passed an argument of "--0.50".
Now, there is no "break" in case 0 of switch. so the control falls through to the next case ( i.e.
case 1) after printing Hello. At case 1, it prints World. And since there is a break. default is not
executed.

Observe that rounding is a standard mathematical procedure where the number that lies exactly
between two numbers always rounds up to the higher one. So .5 rounds to 1 and -.5 rounds to 0.

5) What will the following class print ?

class InitTest{

public static void main(String[] args){

int a = 10;

int b = 20;

a += (a = 4);

b = b + (b = 5);
System.out.println(a+ ", "+b);

You had to select 1 option

a) It will print 8, 25
b) It will print 4, 5
c) It will print 14, 5
d) It will print 4, 25
e) It will print 14, 25

Choose the correct Answer:E

Explanation: a += (a =4) is same as a = a + (a=4).


First, a's value of 10 is kept aside and (a=4) is evaluated. The statement (a=4) assigns 4 to a and
the whole statement returns the value 4. Thus, 10 and 4 are added and assigned back to a.

Same logic applies to b = b + (b = 5); as well.

6) Consider the following classes in one file named A.java...

abstract class A{

protected int m1(){ return 0;

class B extends A{ int m1(){ return 1;

Which of the following statements are correct...

You had to select 1 option

a) The code will not compile as you cannot have more than 1 class in 1 file.
b) The code will not compile because class B does not override the method m1() correctly.
c) The code will not compile as A is an abstract class.
d) The code will not compile as A does not have any abstract method.
e) The code will compile fine.
Choose the correct Answer:B

Explanation: The concept here is that an overriding method cannot make the overridden method more
private.

The access hierarchy in increasing levels of accessibility is:

private->'no modifier'->protected->public ( public is accessible to all and private is accessible to none


except itself.)

Here, class B has no modifier for m1() so it is trying to reduce the accessibility of protected to default.

'protected' means the method will be accessible to all the classes in the same package and all the
subclasses (even if the subclass is in a different package).

No modifier (which is the default level) means the method will be accessible only to all the classes in the
same package. (i.e. not even to the subclass if the subclass is in a different package.)

7) Note: Although Wrapper classes are not explicitly mentioned in the exam objectives, we have seen
some candidates get questions on this aspect of Wrapper classes.

What will be the output of the following program?

public class EqualTest{

public static void main(String args[]){

Integer i = new Integer(1) ;

Long m = new Long(1);

if( i.equals(m)) System.out.println("equal"); // 1

else System.out.println("not equal");

You had to select 1 option

a) Equal
b) not equal
c) Compile time error at //1
d) Runtime error at //1
e) None of the above.

Choose the correct Answer:B


Explanation: Signature of equals method is : boolean equals(Object o); So it can take
any object.
The equals methods of all wrapper classes first check if the two object are of same class or not. If
not, they immediately return false. Hence it will print not equal.

8) Consider the contents of following two files:

//In file A.java

package a;

public class A{

A(){ }

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

//In file B.java

package b;

import a.*;

public class B extends A{

B(){ }

public void print(){ System.out.println("B"); }

public static void main(String[] args){

new B();

What will be printed when you try to compile and run class B?

You had to select 1 option

a) It will print A.
b) It will print B.
c) It will not compile.
d) It will compile but will not run.
e) None of the above.

Choose the correct Answer:C

Explanation: Note that there is no modifier for A's constructor. So it has default access. This means only
classes in package a can use it. Also note that class B is in a different package and is extending from A. In
B's constructor the compiler will automatically add super() as the first line. But since A() is not accessible
in B, this code will not compile.

9) Identify correct option(s)

You had to select 2 option

a) Multiple inheritance of state includes ability to inherit instance methods from multiple classes.
b) Multiple inheritance of state includes ability to inherit instance fields from multiple classes.
c) Multiple inheritance of type includes ability to inherit instance fields as well as instance methods
from multiple classes.
d) Multiple inheritance of type includes ability to implement multiple interfaces and ability to
inherit static or instance fields from interfaces and/or classes.
e) Multiple inheritance of type includes ability to implement multiple interfaces and/or ability to
extend from multiple clases.

Choose the correct Answer:B,E

Explanation: Interfaces, classes, and enums are all "types". Java allows a class to implement multiple
interfaces. In this way, Java supports multiple inheritance of types.

"State", on the other hand, is represented by instance fields. Only a class can have instance fields and
therefore, only a class can have a state. (Fields defined in an interface are always implicitly static, even if
you don't specify the keyword static explicitly. Therefore, an interface does not have any state.) Since a
class is allowed to extend only from one class at the most, it can inherit only one state. Thus, Java does
not support multiple inheritance of state.

This is an important concept and is explained in more detail here:


https://docs.oracle.com/javase/tutorial/java/IandI/multipleinheritance.html

10) The following code snippet will not compile:

int i = 10;

System.out.println( i<20 ? out1() : out2() );

Assume that out1 and out2 methods have the following signatures: public void out1(); and public void
out2();
You had to select 1 option

a) True
b) False
Choose the correct Answer: A
Explanation: Note that it is not permitted for either the second or the third operand expression
of the ? operator to be an invocation of a void method.

If one of the operands is of type byte and the other is of type short, then the type of the
conditional expression is short.
If one of the operands is of type T where T is byte, short, or char, and the other operand is a
constant expression of type int whose value is representable in type T, then the type of the
conditional expression is T.

Otherwise, binary numeric promotion (5.6.2) is applied to the operand types, and the type of
the conditional expression is the promoted type of the second and third operands.
If one of the second and third operands is of the null type and the type of the other is a
reference type, then the type of the conditional expression is that reference type.
If the second and third operands are of different reference types, then it must be possible to
convert one of the types to the other type (call this latter type T) by assignment conversion
(5.2); the type of the conditional expression is T. It is a compile-time error if neither type is
assignment compatible with the other type.

Note that binary numeric promotion performs unboxing conversion (5.1.8) and value set
conversion (5.1.13).

11) Given the following declarations, identify which statements will return true:
Integer i1 = 1;
Integer i2 = new Integer(1);
int i3 = 1;
Byte b1 = 1;
Long g1 = 1L;

You had to select 2 options


a) i1 == i2
b) i1 == i3
c) i1 == b1
d) i1.equals(i2)
e) i1.equals(g1)
f) i1.equals(b1)

Choose the correct Answer:B,D


12) Consider the following code:

class A{

public XXX m1(int a){

return a*10/4-30;

class A2 extends A{

public YYY m1(int a){

return a*10/4.0;

What can be substituted for XXX and YYY so that it can compile without any problems?

You had to select 1 option

a) int, int
b) int, double
c) double, double
d) double, int
e) Nothing, they are simply not compatible.

Choose the correct Answer:C

Explanation: Note that when a method returns objects (as opposed to primitives, like in this
question), the principle of covariant returns applies. Meaning, the overriding method is allowed
to return a subclass of the return type defined in the overridden method. Thus, if a base class's
method is: public A m(); then a subclass is free to override it with: public A1 m(); if
A1 extends A.

13) Which of the following are valid classes?

You had to select 1 option


a) public class ImaginaryNumber extends Number {
//implementation for abstract methods of the base class
}
b) public class ThreeWayBoolean extends Boolean {
//implementation for abstract methods of the base class
}
c) public class NewSystem extends System {
//implementation for abstract methods of the base class
}
d) public class ReverseString extends String {
//implementation for abstract methods of the base class
}

Choose the correct Answer:A

Explanation: String, StringBuilder, and StringBuffer - all are final classes.

1. Remember that wrapper classes for primitives (java.lang.Boolean,


java.lang.Integer, java.lang.Long, java.lang.Short etc.) are also final
and so they cannot be extended.

2. java.lang.Number, however, is not final. Integer, Long, Double etc. extend


Number.

3. java.lang.System is final as well.

14) What will be the result of attempting to compile and run class B?

class A{

final int fi = 10;

public class B extends A{

int fi = 15;

public static void main(String[] args){

B b = new B();

b.fi = 20;
System.out.println(b.fi);

System.out.println( ( (A) b ).fi );

You had to select 1 option

a) It will not compile.


b) It will print 10 and then 10
c) It will print 20 and then 20
d) It will print 10 and then 20
e) It will print 20 and then 10

Choose the correct Answer:E

Explanation: Note that a final variable can be hidden. Here, although fi in A is final, it is hidden
by fi of B. So b.fi = 20; is valid since B's fi is not final.

15) Consider the following method...

public void ifTest(boolean flag){

if (flag) //1

if (flag) //2

System.out.println("True False");

else // 3

System.out.println("True True");

else // 4

System.out.println("False False");

Which of the following statements are correct ?

You had to select 3 option

a) If run with an argument of 'false', it will print 'False False'


b) If run with an argument of 'false', it will print 'True True'
c) If run with an argument of 'true', it will print 'True False'
d) It will never print 'True True'
e) It will not compile.

Choose the correct Answer:A,C,D

Explanation: Note that if and else do not cascade. They are like opening and closing braces.
if (flag) //1
if (flag) //2
System.out.println("True False");
else // 3 This closes //2
System.out.println("True True");
else // 4 This closes //1
System.out.println("False False");

So, else at //3 is associated with if at //2 and else at //4 is associated with if at //1

16) What is the result of executing the following fragment of code:

boolean b1 = false;

boolean b2 = false;

if (b2 != b1 = !b2){

System.out.println("true");

else{

System.out.println("false");

You had to select 1 option

a) Compile time error.


b) It will print true.
c) It will print false.
d) Runtime error.
e) It will print nothing.

Choose the correct Answer:A


Explanation: Note that boolean operators have more precedence than =. (In fact, = has
least precedence of all operators.)
so, in (b2 != b1 = !b2) first b2 != b1 is evaluated which returns a value 'false'. So the
expression becomes false = !b2. And this is illegal because false is a value and not a
variable!

Had it been something like (b2 = b1 != b2) then it is 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 and
as b2 = false is an expression and every expression has a return value (which is actually
the Left Hand Side of the expression). Here, it returns false, which is again a boolean.

Note that return value of expression : i = 10 , where i is an int, is 10 (an int).

17) What will happen on running the following program?

public class DatabaseWrapper

static String url = "jdbc://derby://localhost:1527//mydb";

static DatabaseWrapper getDatabase()

System.out.println("Getting DB");

return null;

public static void main(String[ ] args)

System.out.println( getDatabase().url );

You had to select 1 option

a) It will print Getting DB and jdbc://derby://localhost:1527//mydb


without throwing an exception.
b) It will throw a NullpointerException at Runtime.
c) It will print jdbc://derby://localhost:1527//mydb but will NOT print
Getting DB.
d) It will print Getting DB and then throw a NullPointerException.
e) It will print nothing.

Choose the correct Answer:A

Explanation: This question demonstrates that a null reference may be used to access a class (static)
variable without causing an exception .
Note the method signature. It returns a reference to an object of class DatabaseWrapper.
Thus, getDatabase().url means we are accessing url field of the object returned by the
method. Now, since the class of the object returned by the method is DatabaseWrapper and the
field url is a static field of the class, the compiler creates the instruction for the JVM to access
this field directly using the class reference instead of the object reference returned by the method
at runtime. Thus, the JVM does not need to depend on the actual object returned by the method
at run time to access url. So even if the method returns null at run time, it doesn't matter
because the JVM doesn't even access the reference returned by the method.

18) What will the following code print? System.out.println("12345".charAt(6));

You had to select 1 option

a) 5
b) null
c) -1
d) It will throw an ArrayIndexOutOfBoundsException.
e) It will throw a StringOutOfBoundsException.
f) It will throw an IndexOutOfBoundsException

Choose the correct Answer: f

Choose the correct Answer: Since indexing starts with 0, the maximum value that you can pass to
charAt is length-1.

As per the API documentation for charAt, it throws IndexOutOfBoundsException if


you pass an invalid value (that is, if the index argument is negative or not less than the length of
this string).

Both - ArrayIndexOutOfBoundsException and


StringIndexOutOfBoundsException, extend IndexOutOfBoundsException and
although in practice, the charAt method throws StringIndexOutOfBoundsException,
it is not a valid option because the implementation is free to throw some other exception as long
as it is an IndexOutOfBoundsException.

(There are questions on the exam on this aspect.)

19) Consider the following class:

class TestClass{

void probe(int... x) { System.out.println("In ..."); } //1

void probe(Integer x) { System.out.println("In Integer"); } //2

void probe(long x) { System.out.println("In long"); } //3

void probe(Long x) { System.out.println("In LONG"); } //4

public static void main(String[] args){

Integer a = 4; new TestClass().probe(a); //5

int b = 4; new TestClass().probe(b); //6

What will it print when compiled and run?

You had to select 2 options

a) In Integer and In long


b) In ... and In LONG, if //2 and //3 are commented out.
c) In Integer and In ..., if //4 is commented out.
d) It will not compile, if //1, //2, and //3 are commented out.
e) In LONG and In long, if //1 and //2 are commented out.

Choose the correct Answer: A,D


Explanation: To answer this type of questions, you need to know the following rules:

1. The compiler always tries to choose the most specific method available with least number of
modifications to the arguments.

2. Java designers have decided that old code should work exactly as it used to work before
boxing-unboxing functionality became available.

3. Widening is preferred to boxing/unboxing (because of rule 2), which in turn, is preferred over
var-args.

Thus,
1.
probe(Integer) will be bound to probe(Integer) (exact match). If that is not
available, it will be bound to probe(long), and then with probe(int...) in that order of
preference.
probe(long) is preferred over probe(int...) because unboxing an Integer gives an int
and in pre 1.5 code probe(long) is compatible with an int (Rule 2).

It is never bound to probe(Long ) because Integer and Long are different object types
and there is no IS-A relation between them. (This holds true for any two wrapper classes).
It could, however, be bound to probe(Object ) (if it existed), because Integer IS-A
Object.

2.
probe(int) is bound to probe(long) (because of Rule 2) , then to probe(Integer )
because boxing an int qives you an Integer, which matches exactly to probe(Integer),
and then to probe(int...).

It is never bound to probe(Long ) because int is not compatible with Long.

We advise you to run this program and try out various combinations. The exam has questions on
this pattern but they are not this tough. If you have a basic understanding, you should be ok.

20) The following class will print 'index = 2' when compiled and run.

class Test{

public static int[ ] getArray() { return null; }


public static void main(String[] args){

int index = 1;

try{

getArray()[index=2]++;

catch (Exception e){ } //empty catch

System.out.println("index = " + index);

You had to select 1 option

a) True
b) False

Explanation: If the array reference expression produces null instead of a reference to an array, then a
NullPointerException is thrown at runtime, but only after all parts of the array reference expression
have been evaluated and only if these evaluations completed normally.

This means, first index = 2 will be executed, which assigns 2 to index. After that null[2] is executed,
which throws a NullPointerException. But this exception is caught by the catch block, which prints
nothing. So it seems like NullPointerException is not thrown but it actually is.

In other words, the embedded assignment of 2 to index occurs before the check for array reference
produced by getArray().

In an array access, the expression to the left of the brackets appears to be fully evaluated before any
part of the expression within the brackets is evaluated. Note that if evaluation of the expression to the
left of the brackets completes abruptly, no part of the expression within the brackets will appear to have
been evaluated.

21) What will be the result of attempting to compile and run the following program?

public class TestClass{

public static void main(String args[]){

int x = 0;
labelA: for (int i=10; i<0; i--){

int j = 0;

labelB:

while (j < 10){

if (j > i) break labelB;

if (i == j){

x++;

continue labelA;

j++;

x--;

System.out.println(x);

You had to select 1 option

a) It will not compile.


b) It will go in infinite loop when run.
c) The program will write 10 to the standard output.
d) The program will write 0 to the standard output.
e) None of the above.

Choose the correct Answer:D

Explanation: This is just a simple code that is meant to confuse you.


Notice the for statement: for(int i=10; i<0; i--). i is being initialized to 10 and the test
is i<0, which is false. Therefore, the control will never get inside the for loop, none of the weird
code will be executed, and x will remain 0, which is what is printed.

22) Consider the following class...


class Test{

public static void main(String[ ] args){

int[] a = { 1, 2, 3, 4 };

int[] b = { 2, 3, 1, 0 };

System.out.println( a [ (a = b)[3] ] );

What will it print when compiled and run ?

You had to select 1 option

a) It will not compile.


b) It will throw ArrayIndexOutOfBoundsException when run.
c) It will print 1.
d) It will print 3.
e) It will print 4

Choose the correct Answer:C

Explanation: In an array access, the expression to the left of the brackets appears to be fully
evaluated before any part of the expression within the brackets is evaluated.
In the expression a[(a=b)[3]], the expression a is fully evaluated before the expression
(a=b)[3]; this means that the original value of a is fetched and remembered while the
expression (a=b)[3] is evaluated. This array referenced by the original value of a is then
subscripted by a value that is element 3 of another array (possibly the same array) that was
referenced by b and is now also referenced by a. So, it is actually a[0] = 1.
Note that if evaluation of the expression to the left of the brackets completes abruptly, no part of
the expression within the brackets will appear to have been evaluated.

23) Consider the following code:

interface Bar{

void bar();

abstract class FooBase{

public static void bar(){


System.out.println("In static bar");

public class Foo extends FooBase implements Bar {

What can be done to the above code so that it will compile without any error?

You had to select 1 option

a) Add this method in class Foo -


public void bar(){ };
b) Make the bar method in Bar interface default like this -
default void bar() { }
c) Either of the two approaches presented above will work.
d) Neither of the two approaches presented above will work.
e) Nothing needs to be done. It will compile as it is.

Choose the correct Answer:D

Explanation: The problem with the code is that since Foo extends FooBase, Foo gets the static
method bar() from FooBase in its scope and since Foo also says it implements Bar
interface, it needs to have an instance method bar() with the same signature. This causes a
conflict. A class cannot have two methods with the same signature in its scope where one is
static and one is instance. Therefore, class Foo cannot be a subclass of FooBase and
implement Bar at the same time.

Making the bar method in Bar interface a default method will not help either. Because even
though class Foo will not need have a definition of the bar method in Foo class itself, it will
inherit that method from the Bar interface and the same conflict will occur.

One way to fix the problem is to make the static bar method in class FooBase private. In this
case, class Foo will not have this method in its scope and will therefore be free to implement an
instance method with the same signature.

24) What will the following program print?

class LoopTest{

public static void main(String args[]) {

int counter = 0;
outer:

for (int i = 0; i < 3; i++) {

middle:

for (int j = 0; j < 3; j++) {

inner:

for (int k = 0; k < 3; k++) {

if (k - j > 0) {

break middle;

counter++;

System.out.println(counter);

You had to select 1 option

a) 2
b) 3
c) 6
d) 7
e) 9

Choose the correct Answer:B

Explanation: To understand how this loop works let us put some extra print statements in the
innermost loop:
System.out.println("i="+i+" j="+j+" k="+k);
if(k-j>0){
System.out.println("breaking middle "+j);
break middle;
}
counter++;
This is what it prints:
i=0 j=0 k=0
i=0 j=0 k=1
breaking middle 0
i=1 j=0 k=0
i=1 j=0 k=1
breaking middle 0
i=2 j=0 k=0
i=2 j=0 k=1
breaking middle 0
3
The key is that the middle loop is broken as soon as k-j becomes > 0. This happens on every
second iteration of inner loop when k is 1 and j is 0. Now, when middle is broken inner cannot
continue. So the next iteration of outer starts.

25) Given:

import java.util.*;

public class TestClass {

public static void main(String[] args) throws Exception {

ArrayList<Double> al = new ArrayList<>();

//INSERT CODE HERE

What can be inserted in the above code so that it can compile without any error?

You had to select 2 option

a) al.add(111);
b) System.out.println(al.indexOf(1.0));
c) System.out.println(al.contains("string"));
d) Double d = al.get(al.length);

Choose the correct Answer:B,C

Explanation: Note that al is declared as ArrayList<Double>, therefore the add method is


typed to accept only a Double.
26) What can be the return type of method getSwitch so that this program compiles and runs without
any problems?

public class TestClass{

public static XXX getSwitch(int x){

return x - 20/x + x*x;

public static void main(String args[]){

switch( getSwitch(10) ){

case 1 :

case 2 :

case 3 :

default : break;

You had to select 1 option

a) Int
b) Float
c) Long
d) Double
e) Char
f) Byte
g) Short

Choose the correct Answer:A

Explanation: If you just consider the method getSwitch, any of int long float or double will do.
But the return value is used in the switch statement later on. A switch condition cannot accept
float, long, double, or boolean. So only int is valid.
The return type cannot be byte, short, or char because the expression x - 20/x + x*x;
returns an int.

27) What will the following class print when executed?

class Test{

static boolean a;

static boolean b;

static boolean c;

public static void main (String[] args){

boolean bool = (a = true) || (b = true) && (c = true);

System.out.print(a + ", " + b + ", " + c);

You had to select 1 option

a) true, false, true


b) true, true, false
c) true, false, false
d) true, true, true

Choose the correct Answer:C

Explanation: Java parses the expression from left to right. Once it realizes that the left operand of a
conditional "or" operator has evaluated to true, it does not even try to evaluate the right side
expression.

28) Consider the following classes...

class Teacher{

void teach(String student){

/* lots of code */

}
class Prof extends Teacher{

//1

Which of the following methods can be inserted at line //1 ?

You had to select 4 option

a) public void teach() throws Exception


b) private void teach(int i) throws Exception
c) protected void teach(String s)
d) public final void teach(String s)
e) public abstract void teach(String s)

Choose the correct Answer:A,B,C,D


Explanation: Note that 'protected' is less restrictive than default 'no modifier'. So choice 3 is
valid.
"public abstract void teach(String s)" would have been valid if class Prof had been declared
abstract.

29) Consider the following code:

class A{

A() { print(); }

void print() { System.out.println("A"); }

class B extends A{

int i = 4;

public static void main(String[] args){

A a = new B();

a.print();

void print() { System.out.println(i); }


}

What will be the output when class B is run ?

You had to select 1 option

a) It will print A, 4.
b) It will print A, A
c) It will print 0, 4
d) It will print 4, 4
e) None of the above.

Choose the correct Answer:C

Explanation: Note that method print() is overridden in class B. Due to polymorphism, the
method to be executed is selected depending on the class of the actual object.
Here, when an object of class B is created, first B's default constructor (which is not visible in
the code but is automatically provided by the compiler because B does not define any constructor
explicitly) is called. The first line of this constructor is a call to super(), which invokes A's
constructor. A's constructor in turn calls print(). Now, print is a non-private instance method
and is therefore polymorphic, which means, the selection of the method to be executed depends
on the class of actual object on which it is invoked. Here, since the class of actual object is B, B's
print is selected instead of A's print. At this point of time, variable i has not been initialized
(because we are still in the middle of initializing A), so its default value i.e. 0 is printed.

Finally, 4 is printed.

30) Assume that a, b, and c refer to instances of primitive wrapper classes. Which of the following
statements are correct?

You had to select 2 option

a) a.equals(a) will always return true.


b) b.equals(c) may return false even if c.equals(b) returns true.
c) a.equals(b) returns same as a == b.
d) a.equals(b) throws an exception if they refer to instances of different classes.
e) a.equals(b) returns false if they refer to instances of different classes.

Choose the correct Answer:A,E

Explanation: Equals method of a primitive wrapper class ( e.g. java.lang.Integer, Double, Float
etc) are
1. symmetric => a.equals(b) returns same as b.equals(a)
2. transitive => if a.equals(b) and b.equals(c) return true, then a.equals(c) returns true.
3. reflexive => a.equals(a) return true.

For example, the following code for the equals method on Integer explains how it works:
public boolean equals(Object obj) {
if (obj instanceof Integer) {
return value == ((Integer)obj).intValue();
}
return false;
}

You might also like