Test 5 Failed questions Flashcards

1
Q

Given the following class definition:

class A{ protected int i; A(int i) { this.i = i; } } // 1 : Insert code here

Which of the following would be a valid class that can be inserted at //1 ?

  1. class B {}
  2. class B extends A {}
  3. class B extends A { B() { System.out.println(“i = “ + i); } }
  4. class B { B() {} }
A

– It will print QBANK. – As per Section 12.4.1 given here: http://docs.oracle.com/javase/specs/jls/se7/html/jls-12.html A class or interface type T will be initialized immediately before the first occurrence of any one of the following: T is a class and an instance of T is created. T is a class and a static method declared by T is invoked. A static field declared by T is assigned. A static field declared by T is used and the field is not a constant variable (§4.12.4). T is a top level class (§7.6), and an assert statement (§14.10) lexically nested within T (§8.1.3) is executed. A reference to a static field (§8.3.1.1) causes initialization of only the class or interface that actually declares it, even though it might be referred to through the name of a subclass, a subinterface, or a class that implements an interface. Invocation of certain reflective methods in class Class and in package java.lang.reflect also causes class or interface initialization. A class or interface will not be initialized under any other circumstance

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Consider the following classes: class A implements Runnable { …} class B extends A implements Observer { …} (Assume that Observer has no relation to Runnable.) and the declarations: A a = new A(); B b = new B(); Which of the following Java code fragments will compile and execute without throwing exceptions ? 1 Object o = a; Runnable r = o; 2 Object o = a; Runnable r = (Runnable) o; 3 Object o = a; Observer ob = (Observer) o ; 4 Object o = b; Observer o2 = o; 5 Object o = b; Runnable r = (Runnable) b;

A

2 Object o = a; Runnable r = (Runnable) o; Here you are explicitly telling the compiler that o refers to an object that is Runnable. 5 Object o = b; Runnable r = (Runnable) b; Since b is declared of a type that indirectly implements Runnable, the compiler can figure out that b will always point to an object that is assignable to a Runnable. Therefore, explicit cast is not required here. It will still work fine with the explicit cast though. Although you know that o will refer to an object that is a Runnable at runtime, the compiler doesn’t know about it. That is why, you have to do: Runnable r = (Runnable) o; You can assign a subclass object reference to superclass reference without a cast but to assign a super class object reference to a subclass (or interface) reference you need an explicit cast as in option 2.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

//What, if anything, is wrong with the following code? //Filename: TestClass.java class TestClass implements T1, T2 { public void m1() {} } interface T1 { int VALUE = 1; void m1(); } interface T2 { int VALUE = 2; void m1(); }

A

There is nothing wrong with the code. Having ambiguous fields or methods does not cause any problems by itself but referring to such fields/methods in an ambiguous way will cause a compile time error. So you cannot call : System.out.println(VALUE); because it will be ambiguous (there are two VALUE definitions). But the following lines are valid : TestClass tc = new TestClass(); System.out.println(( ( T1) tc).VALUE); However, explicit cast is not required for calling the method m1() : ( ( T2) tc).m1(); tc.m1() is also fine because even though m1() is declared in both the interfaces, the definition to both resolves unambiguously to only one m1(), which is defined in TestClass.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Given the following class definition:

class A{ protected int i; A(int i) { this.i = i; } } // 1 : Insert code here

Which of the following would be a valid class that can be inserted at //1 ?

A. class B {}

B. class B extends A {}

C. class B extends A { B() { System.out.println(“i = “ + i); } }

D. class B { B() {} }

A
class A{ protected int i; A(int i) { this.i = i; } } // 1 : Insert code here A. class B {} D. class B { B() {} }

Notice that class A does not define a no-argument constructor. Also, note that the class B does not define a constructor.

Thus, class B relies on the default constructor B(). Class B’s default constructor looks like this:

B() {} //It is not public because class B is not public

However, Constructors implicitly (if an explicit call to the superclass’s constructor is not present) call their superclass’s constructor super(). So, class B’s default constructor actually looks like this:

B(){ super(); }

Now, since class A does not define a no-argument constructor the above code will not compile. However, class B would be correct if changed to:

class B extends A{ B(){ super(1); // pass it any integer } // or B(int number){ super(number); } }

You could also add a no-argument constructor to class A and leave class B as is.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Multiple inheritance of type includes the ability to…

A

implement multiple interfaces and/or ability to extend from multiple classes.

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Multiple inheritance of state includes the ability to ..

A

inherit instance fields from multiple classes.

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Which of the given lines can be inserted at //1 of the following program ?

public class TestClass{ 
 public static void main(String[] args){
 short s = 9;
 //1
 }
}
  1. Short k = new Short(9); System.out.println(k instanceof Short);
  2. System.out.println(s instanceof Short);
  3. Short k = 9; System.out.println( k instanceof s);int i = 9;
  4. int i = 9; System.out.println(s == i);
  5. Boolean b = s instanceof Number;
  6. Short k = 9; Integer i = 9; System.out.println(k == i);
  7. Integer i = 9; System.out.println( s == i );
A
  1. Short k = new Short(9); System.out.println(k instanceof Short);
_9 is considered an int and there is no constructor in Short that takes an int._
_Short s = new Short( (short) 9 ); will work_
  1. System.out.println(s instanceof Short);

The left operand of instanceof MUST be a reference variable and not a primitive

  1. Short k = 9; System.out.println( k instanceof s);int i = 9;

Right operand of instanceof MUST be a reference type name, i.e., a class, an interface, or an enum name.

4. int i = 9; System.out.println(s == I); Correct

Any two numeric primitives can be compared using == operator.
Even a numeric primitive and a primitive wrapper (for example, an int with a Short or a Double) can be compared. However, two wrappers of different types (for example, an Integer and a Short) cannot be compared using ==.

  1. Boolean b = s instanceof Number;

Left operand of instanceof MUST be an object and not a primitive

  1. Short k = 9; Integer i = 9; System.out.println(k == i);

This will not compile because k and i are referring to objects that have no IS-A relationship among themselves.

7. Integer i = 9; System.out.println( s == I ); Correct

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

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();

A. True

B. False

A

Note that it is not permitted for the second and the third operand of the ?: operator to be an invocation of a void method.

The type of the expression built using ?: is determined by the types of the second and the third operands.

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).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q
Given:
import java.util.\*;
class Data{
 int value;
 public Data(int x){ this.value = x; }
 public String toString(){ return ""+value; }
}
class MyFilter {
 public boolean test(Data d){
 return d.value == 0;
 }
}

public class TestClass{

public static void filterData(ArrayList<data> dataList, MyFilter f){<br></br> Iterator<data> i = dataList.iterator();<br></br> while(i.hasNext()){<br></br> if(f.test(i.next())){<br></br> i.remove();<br></br> }<br></br> }<br></br> }<br></br><br></br> public static void main(String[] args) {<br></br> ArrayList<data> al = new ArrayList<data>();<br></br> Data d = new Data(1); al.add(d);<br></br> d = new Data(2); al.add(d);<br></br> d = new Data(0); al.add(d);<br></br><br></br> filterData(al, new MyFilter()); //1<br></br><br></br> System.out.println(al);<br></br> }<br></br>}<br></br><br></br>How can you use a lambda expression to achieve the same result?</data></data></data></data>

A. Replace the line at //1 with: filterData(al, x -> x.value==0);

B. Add implements java.util.function.Predicate to MyFilter definition and replace the line at //1 with: filterData(al, x -> x.value==0);

C. Add implements java.util.function.Predicate<data> to MyFilter</data> definition and replace the line at //1 with: filterData(al, x -> x.value==0);

**D.** Remove MyFilter class altogether.
Change type of f from MyFilter to java.util.function.Predicate in filterData method and replace the line at //1 with: **filterData(al, x -\> x.value==0);**
**E**. Remove MyFilter class altogether.
Change type of f from MyFilter to java.util.function.Predicate<data> in filterData method and replace the line at //1 with:<br><strong>filterData(al, x -&gt; x.value==0); </strong></data>
A

A. Replace the line at //1 with: filterData(al, x -> x.value==0);

This would not work because MyFilter is not a functional interface.

B. Add implements java.util.function.Predicate to MyFilter definition and replace the line at //1 with: filterData(al, x -> x.value==0);

This would not work because MyFilter would still not be a functional interface.​

C. Add implements java.util.function.Predicate<data> to MyFilter</data> definition and replace the line at //1 with: filterData(al, x -> x.value==0);

This would not work because MyFilter would still not be a functional interface.​

**D.** Remove MyFilter class altogether.
Change type of f from MyFilter to java.util.function.Predicate in filterData method and replace the line at //1 with: **filterData(al, x -\> x.value==0);**

Predicate is a generified interface. So you need to type it to Data before you can use this lambda expression. Otherwise, the compiler will assume that the type of x is Object and since value is not a valid field in Object class, x.value will cause a the compilation to fail.​

_**E. Remove MyFilter class altogether.
Change type of f from MyFilter to java.util.function.Predicate<data> in filterData method and replace the line at //1 with:</data>**_
**_filterData(al, x -\> x.value==0);_**
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What will the following code print when run without any arguments …

public class TestClass { public static int m1(int i){ return ++i; } public static void main(String[] args) { int k = m1(args.length); k += 3 + ++k; System.out.println(k); } }
  1. It will throw ArrayIndexOutOfBoundsException
  2. It will throw NullPointerException.
  3. 6
  4. 5
  5. 7
  6. 2
  7. None of these
A

When the program is run without any arguments, args gets assigned a string array of size 0. So NullPointerException or ArrayIndexOutOfBoundsException are out of question. Thus, the first call becomes :
int k = m1(0);

Follow through the code like this:
1. Method m1() uses pre-increment operation. Therefore, first i is incremented and then the new value of i is returned.
2. Thus, k gets the value of 1.
3. Expand the += operator as:
k = k + 3 + ++k;

This becomes (remember that k = 1 at this point):
k = 1 + 3 + (++k) i.e.
k = 1 + 3 + 2; (at this point value of k is 2 because of ++k). But the value of Right Hand Side has not yet been assigned to k.
k = 6; 6 is assigned to k thereby overwriting the value of 2.

Therefore, the final value of k is 6.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q
Given:
public class LoopTest {
 int k = 5;
 public boolean checkIt(int k){
 return k--\>0?true:false;
 }
 public void printThem(){
 while(checkIt(k)){
 System.out.print(k);
 }
 }
 public static void main(String[] args) {
 new LoopTest().printThem();
 }
}
What changes should be made so that the program will print 54321?
  1. No change is necessary.
  2. Replace System.out.print(k); with System.out.print(k–);
  3. Replace System.out.print(k); with System.out.print(–k);
  4. Replace while(checkIt(k)) with while(checkIt(–k)).
  5. Replace return k–>0?true:false; with return this.k–>0?true:false
A

2. Replace System.out.print(k); with System.out.print(k–);

Observe that the method parameter k in checkIt shadows the instance variable k. Therefore, any changes made to k in checkIt will not affect the instance variable k. For checkIt method to access the instance variable k, you need to do this.k.

k–>0 means, first compare the value of k with 0, and then reduce it by 1. (As opposed to –k>0, which means, first reduce the value of k by 1 and then compare with 0).

In the printThem method, k refers to the instance variable. You need to reduce it by 1 after each iteration. Therefore, System.out.print(k–); will do.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Consider the following code:

class Super { static String ID = "QBANK"; } class Sub extends Super{ static { System.out.print("In Sub"); } } public class Test{ public static void main(String[] args){ System.out.println(Sub.ID); } }
  1. What will be the output when class Test is run?
  2. It will print In Sub and QBANK
  3. It will print QBANK.
  4. Depends on the implementation of JVM
  5. It will not even compile.
  6. None of the above
A
  1. It will print In Sub and QBANK

As per Section 12.4.1 given here: http://docs.oracle.com/javase/specs/jls/se7/html/jls-12.html

A class or interface type T will be initialized immediately before the first occurrence of any one of the following:

T is a class and an instance of T is created.

T is a class and a static method declared by T is invoked.

A static field declared by T is assigned.

A static field declared by T is used and the field is not a constant variable (§4.12.4).

T is a top level class (§7.6), and an assert statement (§14.10) lexically nested within T (§8.1.3) is executed.

A reference to a static field (§8.3.1.1) causes initialization of only the class or interface that actually declares it, even though it might be referred to through the name of a subclass, a subinterface, or a class that implements an interface.

Invocation of certain reflective methods in class Class and in package java.lang.reflect also causes class or interface initialization.

A class or interface will not be initialized under any other circumstance.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What should be the return type of the following method?

public RETURNTYPE methodX( byte by){ double d = 10.0; return (long) by/d\*3; }
  1. int
  2. long
  3. double
  4. float
  5. byte
A
public RETURNTYPE methodX( byte by){ double d = 10.0; return (long) by/d\*3; }

3. double

Note that the cast (long) applies to ‘by’ not to the whole expression.
( (long) by ) / d * 3;
Now, division operation on long gives you a double.

So the return type should be double.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

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"); } } } }
  1. A
  2. B
  3. C
  4. D
  5. F
A
  1. C and 5. F
  2. 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.
  3. 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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q
Consider the following classes:
class A implements Runnable{ ...}
class B extends A implements Observer { ...}
(Assume that Observer has no relation to Runnable.)

and the declarations :

 A a = new A() ;
 B b = new B();

Which of the following Java code fragments will compile and execute without throwing exceptions?

  1. Object o = a; Runnable r = o;
  2. Object o = a; Runnable r = (Runnable) o;
  3. Object o = a; Observer ob = (Observer) o ;
  4. Object o = b; Observer o2 = o;
  5. Object o = b; Runnable r = (Runnable) b;
A

2. Object o = a; Runnable r = (Runnable) o;

Here you are explicitly telling the compiler that o refers to an object that is Runnable.

5. Object o = b; Runnable r = (Runnable) b;

Since b is declared of a type that indirectly implements Runnable, the compiler can figure out that b will always point to an object that is assignable to a Runnable. Therefore, explicit cast is not required here. It will still work fine with the explicit cast though.

Although you know that o will refer to an object that is a Runnable at runtime, the compiler doesn't know about it. That is why, you have to do: Runnable r = (Runnable) o;
You can assign a subclass object reference to superclass reference without a cast but to assign a superclass object reference to a subclass (or interface) reference you need an explicit cast as in option 2.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What, if anything, is wrong with the following code?

//Filename: TestClass.java
class TestClass implements T1, T2{
 public void m1(){}
}
interface T1{
 int VALUE = 1;
 void m1();
}
interface T2{
 int VALUE = 2;
 void m1();
}
  1. TestClass cannot implement them both because it leads to ambiguity.
  2. There is nothing wrong with the code.
  3. The code will work fine only if VALUE is removed from one of the interfaces.
  4. The code will work fine only if m1() is removed from one of the interfaces.
  5. None of the above.
A

2. There is nothing wrong with the code.

Having ambiguous fields or methods does not cause any problems by itself but referring to such fields/methods in an ambiguous way will cause a compile-time error. So you cannot call:

System.out.println(VALUE);

because it will be ambiguous (there are two VALUE definitions). But the following lines are valid :

TestClass tc = new TestClass();
System.out.println(( ( T1) tc).VALUE);

However, an explicit cast is not required for calling the method m1() :

( ( T2) tc).m1();
tc.m1() is also fine because even though m1() is declared in both the interfaces, the definition to both resolves unambiguously to only one m1(), which is defined in TestClass.

17
Q

Given that SomeException is a checked exception, consider the following code:

//in file A.java
public class A{
 protected void m() throws SomeException{}
}
//in file B.java
public class B extends A{
 public void m(){ }
}
//in file TestClass.java
public class TestClass{
 public static void main(String[] args){
 //insert code here. //1
 }
}

Which of the following options can be inserted at //1 without resulting in any compilation or runtime errors?

  1. B b = new A(); b.m();
  2. A a = new B(); a.m();
  3. A a = new B(); ( ( B) a ).m();
  4. Object o = new B(); o.m()
  5. None of these.
A
  1. B b = new A(); b.m(); –> B b = new A(); is not valid because a superclass object can never be assigned to a base class reference.
  2. A a = new B(); a.m(); –> A’s m() declares ‘throws SomeException’, which is a checked exception, while the main() method doesn’t. So a.m() must be wrapped in a try/catch block.
  3. A a = new B(); ( ( B) a ).m(); –> Due to explicit casting of ‘a’ to B, the compiler knows that ‘a’ will point to an object of class B (or its subclass), whose method m() does not throw an exception. So there is no need for a try-catch block here.
  4. Object o = new B(); o.m() –> Object class does not have method m(). So o.m() will not compile. You can do ( (B) o ).m();
  5. None of these.
18
Q

Which of the following statements will evaluate to true?

  1. “String”.replace(‘g’,’G’) == “String”.replace(‘g’,’G’)
  2. “String”.replace(‘g’,’g’) == new String(“String”).replace(‘g’,’g’)
  3. “String”.replace(‘g’,’G’)==”StrinG”
  4. “String”.replace(‘g’,’g’)==”String”
  5. None of these
A

4. “String”.replace(‘g’,’g’)==”String”

There are 2 points to remember:
1. replace(char oldChar, char newChar) method returns the same String object if both the parameters are same, i.e. if there is no change. Thus, “String” == “String”.replace(‘g’, ‘g’) will return true.

  1. replace(CharSequence oldSeq, CharSequence newSeq) method returns a new String object even if there is no change after replacement. Thus, “String” == “String”.replace(“g”, “g”) will return false.
19
Q

Given:

byte b = 1;
char c = 1;
short s = 1;
int i = 1;

which of the following expressions are valid?

  1. s = b * b ;
  2. i = b + b ;
  3. s *= b ;
  4. c = c + b ;
  5. s += i ;
A

Remember these rules for primitive types:
1. Anything bigger than an int can NEVER be assigned to an int or anything smaller than int ( byte, char, or short) without an explicit cast.

  1. CONSTANT values up to int can be assigned (without cast) to variables of lesser size ( for example, short to byte) if the value is representable by the variable.( that is, if it fits into the size of the variable).
  2. operands of mathematical operators are ALWAYS promoted to AT LEAST int. (i.e. for byte * byte both bytes will be first promoted to int.) and the return value will be AT LEAST int.
  3. Compound assignment operators ( +=, *= etc) have strange ways so read this carefully:

A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T)((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.
Note that the implied cast to type T may be either an identity conversion or a narrowing primitive conversion.
For example, the following code is correct:

short x = 3;
x += 4.6;

and results in x having the value 7 because it is equivalent to:

short x = 3;
x = (short)(x + 4.6);

20
Q

Given the following program, which statements are true?

// Filename: TestClass.java
public class TestClass{
public static void main(String args[]){
A[] a, a1;
B[] b;
a = new A[10]; a1 = a;
b = new B[20];
a = b; // 1
b = (B[]) a; // 2
b = (B[]) a1; // 3
}
}
class A { }
class B extends A { }

  1. Compile time error at line 3
  2. The program will throw a java.lang.ClassCastException at the line labelled 2 when run.
  3. The program will throw a java.lang.ClassCastException at the line labelled 3 when run.
  4. The program will compile and run if the (B[] ) cast in the line 2 and the whole line 3 is removed.
  5. The cast at line 2 is needed.
A
  1. The program will throw a java.lang.ClassCastException at the line labelled 3 when run.
  2. The cast at line 2 is needed.

The line //1 will be allowed during compilation since the assignment is done from a subclass reference to a superclass reference.

The cast in line //2 is needed because a superclass reference is assigned to a subclass reference variable. And this works at runtime because the object referenced to by a is actually of an array of B.

Now, the cast at line //3 tells the compiler not to worry, that I’m a good programmer and I know what I am doing and the object referenced by the superclass reference (a1) will actually be of class B at run time. So there is no compile-time error. But at run time, this fails because the actual object is not an array of B but is an array of