| Java FAQ | ||
| JSP FAQ | ||
| Servlet FAQ | ||
XyzWs Java FAQ:
Can I use an enum type in Java switch statement?
Printer-friendly version |
Mail this to a friend
|
Advertisement
|
Can I use an enum type in Java switch statement?Yes, you can
To clarify, an enum constant is 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
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". |