nerdexam
Oracle

1Z0-819 · Question #110

Given this enum declaration: 1. enum Letter { 2. A(ALPHA(300), BETA(200), GAMMA(300)); 3. int v; 4. 5. Letter(int v) { this.v = v; } 6. / Insert code here / 7. } Examine this code…

The correct answer is C. public String toString() { return String.valueOf(v); }. Option C correctly overrides the toString() method, which System.out.println() calls automatically on any object. By returning String.valueOf(v), the enum instance for BETA (index 1, with v = 200) returns the string "200" instead of its default name "BETA". Why the distractors…

Java Object-Oriented Approach

Question

Given this enum declaration:
  1. enum Letter {
  2. A(ALPHA(300), BETA(200), GAMMA(300));
  3. int v;
  4. Letter(int v) { this.v = v; }
  5. /* Insert code here */
  6. } Examine this code:
System.out.println(Letter.values()[1]); What code should be written at line 5 for the code to print 200?

Options

  • Apublic static Enum <Letter> valueOf(ALPHA[v]) { return ALPHA[v]; }
  • Bpublic String toString() { return String.valueOf(this.v); }
  • Cpublic String toString() { return String.valueOf(v); }
  • Dpublic String toString() { return v; }

How the community answered

(38 responses)
  • A
    3% (1)
  • B
    13% (5)
  • C
    79% (30)
  • D
    5% (2)

Explanation

Option C correctly overrides the toString() method, which System.out.println() calls automatically on any object. By returning String.valueOf(v), the enum instance for BETA (index 1, with v = 200) returns the string "200" instead of its default name "BETA".

Why the distractors are wrong:

  • B (String.valueOf(this.v)) is functionally identical to C in an instance method - both v and this.v refer to the same field - so this is a subtle exam trap; the exam designates C as canonical.
  • D (return v) fails to compile because v is an int and toString() must return a String - Java won't auto-convert here.
  • A introduces completely invalid syntax (ALPHA[v] as a parameter, a static method returning Enum<Letter>) and has nothing to do with printing the field value.

Memory tip: When you see System.out.println(someObject), think "toString() is being called." If the question asks what gets printed, look for the method that returns a String - String.valueOf(primitiveField) is the reliable idiom for converting a numeric field to its string form.

Topics

#enum initialization#toString() override#String conversion#method overriding

Community Discussion

No community discussion yet for this question.

Full 1Z0-819 Practice