Oracle Certified Professional Java Se 8 Programmer · Free Practice Question Hard
Question 8
Consider the code of Test.java file:
- package com.udayan.ocp;
- class Player {
- String name;
- int age;
- Player() {
- this.name = "Sachin";
- this.age = 44;
- }
- public Object toString() {
- return name + ", " + age;
- }
- }
- public class Test {
- public static void main(String[] args) {
- System.out.println(new Player());
- }
- }
What will be the result of compiling and executing Test class?
- A Sachin, 44
- B null, 0
- C Text containing @ symbol
- D Compilation error
Reveal correct answer
Correct answer: D
Explanation
The toString() method in Object class has below definition:
- public String toString() {
- return getClass().getName() + "@" + Integer.toHexString(hashCode());
- }
class Player doesn't override it correctly, return type should be String and not Object.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
You must be logged in to post a comment.
