Java Enum toString vs valueOf Output
Given: What is the result? - 
Community Votes
100% of anonymous learners picked answer C. Votes are pick records left by other test-takers — they are not the verified answer.
Community Insight
The exam tests knowledge of enum internals: ordinal() gives the index (0), while printing an enum calls its toString(), which can be overridden to return any string, such as 'SNOWY'.
This question tests the behavior of Java enums, specifically how ordinal() and overridden toString() methods interact with valueOf(). The correct result is determined by understanding that valueOf returns the enum constant, which triggers the custom toString method.
Learners often choose D or A because they assume the enum prints its name (RAINY or CLOUDY) instead of recognizing that the toString() method has been explicitly overridden to return 'SNOWY'.
Community Discussion (4 comments)
Comments & Corrections
No comments yet — spotted an error or have a note? Share it below.
Expert Analysis
Why the Answer Is Correct
The code defines an enumForecast with constants SUNNY, CLOUDY, and RAINy. The ordinal method returns the zero-based index of the enum constant, so Forecast.SUNNY.ordinal outputs 0. The second part uses Forecast.valueOf("cloudy".toUpperCase), which resolves to Forecast.CLOUDY. When this enum constant is passed to System.out.print, it implicitly calls the toString method. Since toString is overridden to return "SNOWY", the output is 0 SNOWY.Why the Other Options Are Wrong
Options A, B, and D are incorrect because they fail to account for the overriddentoString method. Option A assumes the name is printed but gets the ordinal wrong or confuses the constant. Option B suggests a different ordinal or name. Option D suggests the name is printed without override. Option E is incorrect because the code is syntactically valid Java.Community Comment Notes
The community consensus strongly supports answer C. As user james2033 noted, the code results in0 SNOWY due to the override. User minhdev explained that ordinal gets the index and valueOf returns the constant, triggering the custom toString. Exam Strategy
Always check if an enum has an overridden toString() method when printing enum values. If not overridden, it prints the constant name; if overridden, it prints whatever the method returns.
Frequently Asked Questions
Why does valueOf return CLOUDY but print SNOWY?
valueOf returns the enum constant object Forecast.CLOUDY. When printed, Java calls the object's toString() method, which is overridden to return 'SNOWY'.
Is ordinal always 0 for the first enum?
Yes, ordinal() returns the index of the enum constant in the declaration order. SUNNY is the first constant, so its ordinal is 0.