nerdexam
Oracle

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…

Using Operators and Decision Constructs

Question

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 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")); } } What is the result?

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)
  • A
    15% (3)
  • B
    5% (1)
  • C
    75% (15)
  • D
    5% (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 MyString returns msg via toString(), but no such override exists.
  • B is wrong because StringBuilder does override toString() to return its content - it would not print a hashcode.
  • D is wrong because both classes are in the same package (p1), so Test can access MyString'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

#String concatenation#toString() method#StringBuilder#Object.toString()

Community Discussion

No community discussion yet for this question.

Full 1Z0-808 Practice