enum Color {RED, GREEN, BLUE};
class SwitchEnum
{
public static void main(String[] args)
{
Color c = Color.GREEN;
switch(c)
{
case RED:
System.out.println("red");
break;
case GREEN:
System.out.println("green");
break;
case BLUE:
System.out.println("blue");
break;
}
}
}
The above code compiles fine and gives the expected output.
My question is why when creating the Color reference ‘c’ we needed to refer it through the name of the enum (i.e. Color.GREEN) but in the case block only the enum value sufficed. Shouldn’t it have been
case Color.RED:
etc???
No, it shouldn’t. The Java compiler is smart enough to know that you are switching on a
Colorand so the language allows for this shortcut (and as Paul notes, requires it). In fact, the whole compilation of a switch statement depends on the compiler knowing what you’re switching on, since it translates the switch into a jump table based on the index of the enum value you specify. Only very recently have you been able to switch on non-numerical things like aString.The relevant part of the language spec is in JLS Chapter 14.11:
If you’re looking for insight into why the language was designed the way it was, that’s going to be hard to answer objectively. Language design is nuanced, and you have to consider that the assignment syntax was written years and years before enum support was added.