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)- A3% (1)
- B6% (2)
- C3% (1)
- D11% (4)
- E78% (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()returns0becauseSUNNYis declared first in the enum (ordinals are zero-indexed: SUNNY=0, CLOUDY=1, RAINY=2). This eliminates A and C (which show1).Forecast.valueOf("CLOUDY".toUpperCase())resolves to theCLOUDYenum constant. When passed toSystem.out.print(), itstoString()is called. SinceForecastdoes not overridetoString(), it inherits fromjava.lang.Enum, which returns the constant's name -"CLOUDY". Output:0 CLOUDY.
Why each distractor fails:
- A (1 RAINY):
SUNNY.ordinal()is0, not1; andvalueOf("CLOUDY")cannot produceRAINY. - B (Compilation fails): All syntax is valid -
ordinal(),valueOf(), andtoUpperCase()are all legal calls here. - C (1 Snowy): Ordinal is wrong (
0, not1), and thetoString()override is onWeather, notForecast. - E (0 Snowy): The critical trap -
WeatheroverridestoString()to return"SNOWY", butForecastis a separate type extendingjava.lang.Enum, notWeather. 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.