Oracle Certified Professional Java Se 8 Programmer · Free Practice Question Hard
Question 14
Given code of Test.java file:
- package com.udayan.ocp;
- public class Test<T> {
- private T t;
- public T get() {
- return t;
- }
- public void set(T t) {
- this.t = t;
- }
- public static void main(String args[]) {
- Test obj = new Test();
- obj.set("OCP");
- obj.set(85);
- obj.set('%');
- System.out.println(obj.get());
- }
- }
What will be the result of compiling and executing Test class?
- A %
- B Runtime exception
- C Compilation error
- D OCP85%
- E Output contains some text containing @ symbol
Reveal correct answer
Correct answer: A
Explanation
Test<T> is generic type and Test is raw type. When raw type is used then T is Object, which means set method will have signature: set(Object t).
Test obj = new Test(); => Test object is created and obj refers to it.
obj.set("OCP"); => Instance variable t refers to "OCP".
obj.set(85); => Instance variable t refers to Integer object, 85. Auto-boxing converts int literal to Integer object.
obj.set('%'); => Instance variable t refers to Character object, %. Auto-boxing converts char literal to Character object.
obj.get() => this returns Character object as Character class overrides toString() method, % is printed on to the console.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
