Java Enum (Enumerations)An enum is just like any other Java Class, with a predefined set of instances. It is basically a data type that lets you describe each member of a type in a more readable and reliable way, for example, temperature level like High, Medium and Low.
The main advantage of Enum is that it make your code more explicit, less error-prone and in a self-documenting way.
When should I use?You can use enum types any time you need to represent a fixed set of constants .
You can use enums when a variable (especially a method parameter) can only take one out of a small set of possible values. Examples would be things like days in a Week(Sunday, Monday etc..), or Directions (NORTH, SOUTH, EAST and WEST).You can use an enum instead of a class if the class should have a fixed enumerable number of instances.
Enum switch...case Example :You can also use an enum type in a Java switch...case statement. You can use Enum in Java inside the Switch statement like int or char primitive data type.
The following program shows how to use Enum in switch...case statement.
Enum if...esle Example :You can also use an enum type in a Java if..else statement. The following program shows how to use Enum in if..else statement.
Enum for loop Example :
The following Java program shows how to use Enum in for loop.
Points to remember for Java Enum
- Enum considered more type-safe than constants: One of the common use of enums is to prevent the possibility of an invalid parameter.
For example, consider a normal method like the following:
The above method is not only ambiguous (do day indexes start at 1, or at 0?), but you can give down-right invalid data like greater than 7 or negative numbers. Instead, if you have an enum DAYS with Sunday, Monday, etc. the signature becomes:
Code calling this method will be far more readable, and can't provide invalid data.
Using enum over constants helps with type safety because if a function takes an enum and you pass it anything but an enum, the compiler will complain. With constants, you're accepting a pretty large range of data, most of which are invalid.
- java.util.EnumSet & java.util.EnumMap: Two classes have been added to java.util to support enum: EnumSet and EnumMap. They are high performance implementation of the Set and Map interfaces respectively.
- All constants defined in an enum are public static final. Since they are static, they can be accessed via EnumName.instanceName.
- An enum can be declared outside or inside a class, but NOT in a method.
- Adding new constants on Enum in Java is easy and you can add new constants without breaking the existing code.