1Z0-819 · Question #40
Given this enum declaration: 1. enum Alphabet { 2. A, B, C 3. } 4. Examine this code: System.out.println(Alphabet.getFirstLetter()); What line should be written at line 3 to make the code print A?
The correct answer is C. static String getFirstLetter() { return A.toString(); }. Option C is correct because getFirstLetter() must be static (called on the class itself via Alphabet.getFirstLetter(), not on an instance), and within an enum body, you can reference other enum constants like A directly without qualification, so A.toString() returns "A". Why…
Question
- enum Alphabet {
- A, B, C
- }
Options
- AString str = getFirstLetter(). (return A.toString())
- Bstatic String getFirstLetter() { return Alphabet.values()[1].toString(); }
- Cstatic String getFirstLetter() { return A.toString(); }
- DString getFirstLetter(). (return A.toString())
How the community answered
(27 responses)- A4% (1)
- B4% (1)
- C81% (22)
- D11% (3)
Explanation
Option C is correct because getFirstLetter() must be static (called on the class itself via Alphabet.getFirstLetter(), not on an instance), and within an enum body, you can reference other enum constants like A directly without qualification, so A.toString() returns "A".
Why the distractors fail:
- A - missing
static, making it an instance method; also the syntaxgetFirstLetter(). (return ...)is invalid Java. - B - is static and syntactically valid, but
values()[1]returns the second element (B, since arrays are 0-indexed), notA(values()[0]). - D - same problem as A: missing
static, so it can't be called asAlphabet.getFirstLetter().
Memory tip: When you see a method called on the class name (not an object), it must be static - eliminate any option without it immediately. Then double-check array indices: values()[0] = first constant, values()[1] = second.
Topics
Community Discussion
No community discussion yet for this question.