Java OCA OCP Practice Question 2680

Question

What is the result of the following code?

1:    public class Hello<T> { 
2:       T t; 
3:       public Hello(T t) { this.t = t; } 
4:       public String toString() { return t.toString(); } 
5:       public static void main(String[] args) { 
6:          System.out.print(new Hello<String>("hi")); 
7:          System.out.print(new Hello("there")); 
8:       } 
9:    } 
A.  hi
B.  hi followed by a runtime exception
C.  hithere
D.  Compiler error on line 4
E.  Compiler error on line 6
F.  Compiler error on line 7


C.

Note

Line 7 gives a compiler warning for not using generics but not a compiler error.

Line 4 compiles fine because toString() is defined on the Object class and is therefore always available to call.

Line 6 creates the Hello class with the generic type String.

Line 7 creates the Hello class with the generic type Object since no type is specified.




PreviousNext

Related