nerdexam
Oracle

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…

Java Object-Oriented Approach

Question

Given this enum declaration:
  1. enum Alphabet {
  2. A, B, C
  3. }
Examine this code: System.out.println(Alphabet.getFirstLetter()); What line should be written at line 3 to make the code print A?

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)
  • A
    4% (1)
  • B
    4% (1)
  • C
    81% (22)
  • D
    11% (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 syntax getFirstLetter(). (return ...) is invalid Java.
  • B - is static and syntactically valid, but values()[1] returns the second element (B, since arrays are 0-indexed), not A (values()[0]).
  • D - same problem as A: missing static, so it can't be called as Alphabet.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

#enums#static methods#enum constants#method declarations

Community Discussion

No community discussion yet for this question.

Full 1Z0-819 Practice