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…
Question
- enum Letter {
- A(ALPHA(300), BETA(200), GAMMA(300));
- int v;
- Letter(int v) { this.v = v; }
- /* Insert code here */
- } Examine this code:
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)- A3% (1)
- B13% (5)
- C79% (30)
- D5% (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 - bothvandthis.vrefer to the same field - so this is a subtle exam trap; the exam designates C as canonical. - D (
return v) fails to compile becausevis anintandtoString()must return aString- Java won't auto-convert here. - A introduces completely invalid syntax (
ALPHA[v]as a parameter, a static method returningEnum<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
Community Discussion
No community discussion yet for this question.