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".
Most Recent java Faqs
- How to uncompress a file in the gzip format?
- How to make a gzip file in Java?
- How to use Java String.split method to split a string by dot?
- How to validate URL in Java?
- How to schedule a job in Java?
- How to return the content in the correct encoding from a servlet?
- What is the difference between JDK and JRE?
Most Viewed java Faqs
- How to read input from console (keyboard) in Java?
- How to use HttpURLConnection POST data to web server?
- How to add BASIC Authentication into HttpURLConnection?
- How to Retrieve Multiple Result Sets from a Stored Procedure in JDBC?
- What are class variables in Java?
- What are local variables in Java?
- How to Use Updatable ResultSet in JDBC?