Home  |   STIU  |   WOW  |   SCJP  |   SCDJWS   |   JEE FAQ  |   About US  |  

FAQ
  Java FAQ
  JSP FAQ
  Servlet FAQ
 

Advertisement

XyzWs Java FAQ:
Can I use an enum type in Java switch statement?


Printer-friendly version Printer-friendly version | Send this 
article to a friend Mail this to a friend


Previous Next vertical dots separating previous/next from contents/index/pdf Contents
Advertisement
XyzWs Java FAQ: Can I use an enum type in Java switch statement?

Can I use an enum type in Java switch statement?

Yes, you can

To clarify, an enum constant is not a constant expression as defined by the Java Language Speicification 3rd Edition. This is because an enum constant is not really constant, but created during class initialization of the enum type.

For this reason the rules for the switch statement were extended to include enum constants (14.11 The switch Statement):

SwitchLabel:
        case ConstantExpression :
        case EnumConstantName :
        default :

EnumConstantName:
        Identifier

Notice : Enum constants a switch label are unqualified identifiers. In another words, the enum value in the case switch label must be an unqualified name. It inherits the context from the type of the object in the switch() clause, and that cases can simply use unqualified names.

public class EnumExample{  
  enum Animal{HORSE,CAT,DOG};  
  public static void main(String args[])  {
    Animal animal = Animal.DOG;
    switch(animal) {
      case Animal.HORSE : break; //compiler-time error 
      case CAT : break;
      case DOG : break;
    }
  }
}

You will get a compile time error "an enum switch case label must be the unqualified name of an enumeration constant".


Previous Next vertical dots separating previous/next from contents/index/pdf Contents

Support  | Feedback  | Help