1Z0-808 · Question #13
Given the definitions of the MyString class and the Test class: MyString.java: package p1; class MyString { String msg; MyString(String msg) { this.msg = msg; } } Test.java: package p1; public class…
The correct answer is C. Hello Java SE 8 Hello p1.MyString@<hashcode>>. Option C is correct because Java's string concatenation operator (+) implicitly calls toString() on each operand. StringBuilder overrides toString() to return its character sequence, so "Hello " + new StringBuilder("Java SE 8") produces "Hello Java SE 8". However, MyString does…
Question
Options
- AHello Java SE 8 Hello Java SE 8
- BHello java.lang.StringBuilder@<hashcode1>> Hello p1.MyString@<hashcode2>>
- CHello Java SE 8 Hello p1.MyString@<hashcode>>
- DCompilation fails at the Test class.
How the community answered
(20 responses)- A15% (3)
- B5% (1)
- C75% (15)
- D5% (1)
Explanation
Option C is correct because Java's string concatenation operator (+) implicitly calls toString() on each operand. StringBuilder overrides toString() to return its character sequence, so "Hello " + new StringBuilder("Java SE 8") produces "Hello Java SE 8". However, MyString does not override toString(), so it inherits Object.toString(), which returns the format fully.qualified.ClassName@hexHashCode - giving "Hello p1.MyString@<hashcode>".
Why the distractors are wrong:
- A is wrong because it assumes
MyStringreturnsmsgviatoString(), but no such override exists. - B is wrong because
StringBuilderdoes overridetoString()to return its content - it would not print a hashcode. - D is wrong because both classes are in the same package (
p1), soTestcan accessMyString's package-private constructor without any compilation error.
Memory tip: Think of it as a "contract" rule - only classes that explicitly override toString() get readable output during string concatenation. If you didn't write toString(), Java gives you the ugly ClassName@hashcode default from Object. Built-in classes like StringBuilder, String, and wrappers (Integer, etc.) always override it; your custom classes do not unless you write it yourself.
Topics
Community Discussion
No community discussion yet for this question.