1z0-808 Exam QuestionsBrowse all questions from this exam

1z0-808 Exam - Question 54


Given the definitions of the MyString class and the Test class:

What is the result?

A.

B.

C.

D. Compilation fails at the Test class

Show Answer
Correct Answer:

The correct answer is C. In the provided code, the `StringBuilder` class has an overridden `toString` method, which returns the string content when concatenated with another string. Hence, `new StringBuilder("Java SE 8")` will give the output as `Hello Java SE 8`. On the other hand, the `MyString` class does not override the `toString` method from the `Object` class. As a result, when an instance of `MyString` is concatenated with a string, it will call the default `toString` method from the `Object` class, which returns the class name followed by the `@` symbol and the object's hashcode. So, the second print statement will produce an output like `Hello p1.MyString@<hashcode>`. Therefore, the final output is `Hello Java SE 8` and `Hello p1.MyString@<hashcode>`.

Discussion

4 comments
Sign in to comment
iSnover
Oct 4, 2023

The correct one is the letter C and it has been tested. The reason for presenting the hashcode is because the MyString object does not have the to String method, whereas the Stringbuilder does, which is why it printed correctly.

DriftKing
Aug 31, 2024

Answer is C. Code - class MyString { String msg; MyString(String msg) { this.msg=msg; } } // Since both classes are in same package public class Test { public static void main(String[] args) { System.out.println("Hello "+ new StringBuilder("Java SE 8")); System.out.println("Hello "+ new MyString("Java SE 8")); } }

UAK94
Oct 13, 2023

Answer is C. Tested.

Ankit1010
Feb 7, 2024

Correct Answer is C