Enum in java is a data type that contains fixed set of constants. The Java Enum constants are static and final implicitly. It is available from JDK 1.5.
Points to remember for Java Enum
Simple example of Java Enum
class Example1{ public enum Season {WINTER, SPRING, SUMMER, FALL}; Season w = Season.WINTER; public static void main(String[] args) { for (Season s : Season.values()) System.out.println(s); } } #Output:WINTER # SPRING # SUMMER # FALL
The Java Compiler automatically generates a static method for each enum, called values
. This method returns an array of all constants defined inside the enum. Notice that the values are returned in the same order as they were initially defined.
The Enum constants have initial value that starts from 0, 1, 2, 3 and so on. But we can initialize the specific value to the Enum constants by defining fields and constructors.
Enum in Java are reference types like class or interface and you can define constructor, methods and variables inside java Enum.
Example of specifying initial value to the Enum constants
class Example2{ enum Season{ WINTER(10), SPRING(20), SUMMER(30), FALL(40); private int value; private Season(int value){ this.value = value; } public int getValue() { return value; } } public static void main(String args[]){ for (Season s : Season.values()) System.out.println(s + " " + s.value); } }
Enums have their own namespace and they can be used in a switch
statement, in the same way as integers.
class Example3{ enum Day{SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY}; public static void main(String args[]){ Day day = Day.MONDAY; switch(day){ case SUNDAY: case SATURDAY: System.out.println("weekend"); break; case MONDAY: case TUESDAY: case WEDNESDAY: case THURSDAY: case FRIDAY: System.out.println("workday"); break; } } }
An EnumMap
is a specialized Map
implementation. All of the keys in an EnumMap
must come from a single Enum type that is specified, explicitly or implicitly, when the map is created. EnumMaps
are represented internally as arrays. Also, EnumMaps
are maintained in the natural order of their keys.
An EnumSet
is a specialized Set
implementation. All of the elements in an EnumSet
must come from a single Enum type that is specified, explicitly or implicitly, when the set is created. EnumSet
are represented internally as bit vectors. Also, an iterator traverses the elements in their natural order.