Enum - Answer for Constants in Java
Join the DZone community and get the full member experience.
Join For FreeEnum is a java keyword and very useful in our everyday programming. We use Enum for a variable to be set of a predefined constant value.
Before Java 1.5 we used public static final keywords to represent constants. Enum was introduced in Java 1.5 and since then we use it represent constants or string name for a variable. Also Enums are thread safe by default.
public enum Status { COMPLETED(7), FAILED(9), STARTED(3), IN_PROGRESS(6); private int statusValue; private Status (int statusValue) { this. statusValue = statusValue; } }
Here Status is the Enum and COMPLETED, FAILED, STARTED, IN_PROGRESS are Enum contant values. Enum contastants are static and final by default and cannot be changed after once it is created. Also Enums can be used in Switch statements like int and char data types.
We can define values for enum constants at the time of creation, but then we must add a constructor and a field variable for this enum. Enum constructor must be always private. If we use any other modifier, compiler will throw an error.
- Enums can be used in Switch case statements like shown below
Status status = Status.COMPLETED; switch (status) { case STARTED: System.out.println("Application started"); break; case FAILED: System.out.println("Application failed"); break; case COMPLETED: System.out.println("Application completed"); break; default: throw new IllegalArgumentException("Invalid Invocation"); }
- Enums can implement any interface and override methods
- Enum in java implicitly implement both Serializable and Comparable interface
public enum Status implements Runnable { COMPLETED(7), FAILED(9), STARTED(3), IN_PROGRESS(6); private int statusValue; private Status (int statusValue) { this. statusValue = statusValue; } @Override public void run() { System.out.println("Within run method"); } }
- Abstact methods can be implemented in Enums can provide different implementations for different Enum constants
- We can create a list directly from the Enum constants using the values() method
List<PodSchdEnumConstants> al = Arrays.asList(PodSchdEnumConstants.values());
Opinions expressed by DZone contributors are their own.
Comments