Test 5 Failed questions Flashcards
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 ?
- class B {}
- class B extends A {}
- class B extends A { B() { System.out.println(“i = “ + i); } }
- class B { B() {} }
– 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
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;
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.
//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(); }
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.
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() {} }
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.
Multiple inheritance of type includes the ability to…
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.
Multiple inheritance of state includes the ability to ..
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.
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 } }
- Short k = new Short(9); System.out.println(k instanceof Short);
- System.out.println(s instanceof Short);
- Short k = 9; System.out.println( k instanceof s);int i = 9;
- int i = 9; System.out.println(s == i);
- Boolean b = s instanceof Number;
- Short k = 9; Integer i = 9; System.out.println(k == i);
- Integer i = 9; System.out.println( s == i );
- 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_
- System.out.println(s instanceof Short);
The left operand of instanceof MUST be a reference variable and not a primitive
- 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 ==.
- Boolean b = s instanceof Number;
Left operand of instanceof MUST be an object and not a primitive
- 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
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
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).
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 -> x.value==0); </strong></data>
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);_**
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); } }
- It will throw ArrayIndexOutOfBoundsException
- It will throw NullPointerException.
- 6
- 5
- 7
- 2
- None of these
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.
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?
- No change is necessary.
- Replace System.out.print(k); with System.out.print(k–);
- Replace System.out.print(k); with System.out.print(–k);
- Replace while(checkIt(k)) with while(checkIt(–k)).
- Replace return k–>0?true:false; with return this.k–>0?true:false
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.
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); } }
- What will be the output when class Test is run?
- It will print In Sub and QBANK
- It will print QBANK.
- Depends on the implementation of JVM
- It will not even compile.
- None of the above
- 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.
What should be the return type of the following method?
public RETURNTYPE methodX( byte by){ double d = 10.0; return (long) by/d\*3; }
- int
- long
- double
- float
- byte
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.
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"); } } } }
- A
- B
- C
- D
- F
- C and 5. F
- 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.
- 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.
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?
- Object o = a; Runnable r = o;
- Object o = a; Runnable r = (Runnable) o;
- Object o = a; Observer ob = (Observer) o ;
- Object o = b; Observer o2 = o;
- Object o = b; Runnable r = (Runnable) b;
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.