nerdexam
Oracle

1Z0-829 · Question #17

public class Weather { public enum Forecast { SUNNY, CLOUDY, RAINY; } @Override public String toString() { return "SNOWY";} public static void main(String[] args) {…

The correct answer is E. 0 Snowy. Option E as marked appears to be incorrect - the actual correct answer is D: 0 CLOUDY. Here's why: Why D is correct: Forecast.SUNNY.ordinal() returns 0 because SUNNY is declared first in the enum (ordinals are zero-indexed: SUNNY=0, CLOUDY=1, RAINY=2). This eliminates A and C…

Utilizing Java Object-Oriented Approach

Question

public class Weather { public enum Forecast { SUNNY, CLOUDY, RAINY; } @Override public String toString() { return "SNOWY";} public static void main(String[] args) { System.out.print(Forecast.SUNNY.ordinal() + " "); System.out.print(Forecast.valueOf("CLOUDY".toUpperCase())); } } What is the result?

Options

  • A1 RAINY
  • BCompilation fails
  • C1 Snowy
  • D0 CLOUDY
  • E0 Snowy

How the community answered

(36 responses)
  • A
    3% (1)
  • B
    6% (2)
  • C
    3% (1)
  • D
    11% (4)
  • E
    78% (28)

Explanation

Option E as marked appears to be incorrect - the actual correct answer is D: 0 CLOUDY. Here's why:

Why D is correct:

  • Forecast.SUNNY.ordinal() returns 0 because SUNNY is declared first in the enum (ordinals are zero-indexed: SUNNY=0, CLOUDY=1, RAINY=2). This eliminates A and C (which show 1).
  • Forecast.valueOf("CLOUDY".toUpperCase()) resolves to the CLOUDY enum constant. When passed to System.out.print(), its toString() is called. Since Forecast does not override toString(), it inherits from java.lang.Enum, which returns the constant's name - "CLOUDY". Output: 0 CLOUDY.

Why each distractor fails:

  • A (1 RAINY): SUNNY.ordinal() is 0, not 1; and valueOf("CLOUDY") cannot produce RAINY.
  • B (Compilation fails): All syntax is valid - ordinal(), valueOf(), and toUpperCase() are all legal calls here.
  • C (1 Snowy): Ordinal is wrong (0, not 1), and the toString() override is on Weather, not Forecast.
  • E (0 Snowy): The critical trap - Weather overrides toString() to return "SNOWY", but Forecast is a separate type extending java.lang.Enum, not Weather. That override has zero effect on enum constants.

Memory tip: An enum nested inside a class does NOT inherit from the outer class - it always extends java.lang.Enum. A toString() override on the outer class is completely invisible to the enum's string representation.

Topics

#enums#ordinal()#valueOf()#toString() override

Community Discussion

No community discussion yet for this question.

Full 1Z0-829 Practice