Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

enum referencing in switch case

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???

like image 647
Surender Thakran Avatar asked May 11 '12 04:05

Surender Thakran


People also ask

Can enum be used in switch case?

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 switch case statement?

Can enum be checked in a switch-case statement? Yes. Enum can be checked. As an integer value is used in enum.

Can enum throw exception?

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.

Can we use float in switch case?

Switch case allows only integer and character constants in case expression. We can't use float values.


1 Answers

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.

like image 162
Mark Peters Avatar answered Sep 29 '22 19:09

Mark Peters