Very Tough Test 9
Very Tough Test 9
int i = 1;
int j = i++;
if( (i==++j) | (i++ == j) ){
i+=j;
}
System.out.println(i);
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.
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?
char i;
switch(i++){
case 4: System.out.println("E");
a) A
b) B
c) C
d) D
e) F
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.
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?
4) Given:
switch(getSwitch(args[0])){
}
}
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.)
a) Hello
b) World
c) Hello World
d) Hello World Good Bye
e) Good Bye
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.
class InitTest{
int a = 10;
int b = 20;
a += (a = 4);
b = b + (b = 5);
System.out.println(a+ ", "+b);
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
abstract class A{
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.
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.
a) Equal
b) not equal
c) Compile time error at //1
d) Runtime error at //1
e) None of the above.
package a;
public class A{
A(){ }
package b;
import a.*;
B(){ }
new B();
What will be printed when you try to compile and run class B?
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.
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.
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.
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.
int i = 10;
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;
class A{
return a*10/4-30;
class A2 extends A{
return a*10/4.0;
What can be substituted for XXX and YYY so that it can compile without any problems?
a) int, int
b) int, double
c) double, double
d) double, int
e) Nothing, they are simply not compatible.
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.
14) What will be the result of attempting to compile and run class B?
class A{
int fi = 15;
B b = new B();
b.fi = 20;
System.out.println(b.fi);
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.
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");
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
boolean b1 = false;
boolean b2 = false;
if (b2 != b1 = !b2){
System.out.println("true");
else{
System.out.println("false");
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.
System.out.println("Getting DB");
return null;
System.out.println( getDatabase().url );
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.
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: Since indexing starts with 0, the maximum value that you can pass to
charAt is length-1.
class TestClass{
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...).
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{
int index = 1;
try{
getArray()[index=2]++;
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?
int x = 0;
labelA: for (int i=10; i<0; i--){
int j = 0;
labelB:
if (i == j){
x++;
continue labelA;
j++;
x--;
System.out.println(x);
int[] a = { 1, 2, 3, 4 };
int[] b = { 2, 3, 1, 0 };
System.out.println( a [ (a = b)[3] ] );
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.
interface Bar{
void bar();
What can be done to the above code so that it will compile without any error?
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.
class LoopTest{
int counter = 0;
outer:
middle:
inner:
if (k - j > 0) {
break middle;
counter++;
System.out.println(counter);
a) 2
b) 3
c) 6
d) 7
e) 9
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.*;
What can be inserted in the above code so that it can compile without any error?
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);
switch( getSwitch(10) ){
case 1 :
case 2 :
case 3 :
default : break;
a) Int
b) Float
c) Long
d) Double
e) Char
f) Byte
g) Short
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.
class Test{
static boolean a;
static boolean b;
static boolean 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.
class Teacher{
/* lots of code */
}
class Prof extends Teacher{
//1
class A{
A() { print(); }
class B extends A{
int i = 4;
A a = new B();
a.print();
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.
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?
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;
}