Oracle Certified Professional Java Se 11 Developer · Free Practice Question Hard
Question 38
Question ID: UKOCP27708
Given code of Test.java file:
- package com.udayankhattry.ocp;
- class Printer<String> {
- private String t;
- Printer(String t){
- this.t = t;
- }
- public String toString() {
- return null;
- }
- }
- public class Test {
- public static void main(String[] args) {
- Printer<Integer> obj = new Printer<>(100);
- System.out.println(obj);
- }
- }
What will be the result of compiling and executing Test class?
- A 100
- B null
- C Compilation error in Printer class
- D Compilation error in Test class
Reveal correct answer
Correct answer: C
Explanation
UKOCP27708:
Type parameter should not be a Java keyword & a valid Java identifier. Naming convention for Type parameter is to use uppercase single character.
In class Printer<String>, 'String' is a valid Java identifier and hence a valid type parameter even though it doesn't follow the naming convention of uppercase single character.
But within Printer<String> class, 'String' is considered as type parameter and not java.lang.String class. Return value of toString() method is java.lang.String class and not type parameter 'String'. So toString() method caused compilation error in Printer class.
To resolve the compilation error, you can use below code:
- public java.lang.String toString() {
- return null;
- }
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
