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???
We can use also use Enum keyword with Switch statement. We can use Enum in Switch case statement in Java like int primitive.
Can enum be checked in a switch-case statement? Yes. Enum can be checked. As an integer value is used in enum.
The Problem. Using Enum. valueOf is great when you know the input is valid. However, if you pass in an invalid name, an exception will be thrown.
Switch case allows only integer and character constants in case expression. We can't use float values.
No, it shouldn't. The Java compiler is smart enough to know that you are switching on a Color
and 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 a String
.
The relevant part of the language spec is in JLS Chapter 14.11:
... SwitchLabel: case ConstantExpression : case EnumConstantName : default : EnumConstantName: Identifier
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With