Enumerations (often referred to simply as enum) are fixed sets of closely related items. For instance, "North", "South", "East", and "West". The enum named CardinalDirections would have only those four options.
Enumerations can and should be used often. They are a great alternative to using String or int for a set of final or predefined variables which can quickly lead to inconsistencies.
How to Use Java Enum?
An enum type is a distinctive data type that allows a variable to represent a predefined set of constants. The variable's value can only be set to one of the predefined values assigned to the enum.
Common Enum Examples
Below are some common situations where enums can be nicely used.
| Example | Values |
|---|---|
| Cardinal directions | NORTH, SOUTH, EAST, WEST |
| Types of novels | MYSTERY, CLASSIC, FANTASY, ROMANCE, SCIENCE-FICTION |
| Flavours of ice cream | CHOCOLATE, VANILLA, RASPBERRY, MAPLE |
| Days of the week | MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY |
The Java syntax convention for "constants" or final variables is to use all UPPER CASE. That is why the potential values in the enum are all capitalized. These values cannot change. They are effectively final.
Java Example Enum
You define an enum in much the same way you define a class. For example:
public enum Day {
SUNDAY,
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY;
}
Use enum types whenever you need to model a constant and unchanging set of values. For instance, the planets within our solar system, days of the week, cardinal directions, and other datasets where you have prior knowledge of all conceivable values - such as menu choices, command line flags, and similar scenarios.
To use an enum, you simply type the name of the enum, then the name of the constant value inside the enum. For instance, Day.MONDAY
Day Enum Example
Here is some code that shows you how to use the Day enum defined above. This example comes from the Oracle docs.
public class EnumTest {
// Day below is an enum
Day day;
public EnumTest(Day day) {
this.day = day;
}
public void tellItLikeItIs() {
switch (day) {
case MONDAY:
System.out.println("Mondays are bad.");
break;
case FRIDAY:
System.out.println("Fridays are better.");
break;
case SATURDAY: case SUNDAY:
System.out.println("Weekends are best.");
break;
default:
System.out.println("Midweek days are so-so.");
break;
}
}
public static void main(String[] args) {
EnumTest firstDay = new EnumTest(Day.MONDAY);
firstDay.tellItLikeItIs();
EnumTest thirdDay = new EnumTest(Day.WEDNESDAY);
thirdDay.tellItLikeItIs();
EnumTest fifthDay = new EnumTest(Day.FRIDAY);
fifthDay.tellItLikeItIs();
EnumTest sixthDay = new EnumTest(Day.SATURDAY);
sixthDay.tellItLikeItIs();
EnumTest seventhDay = new EnumTest(Day.SUNDAY);
seventhDay.tellItLikeItIs();
}
}
/*
Output:
> Mondays are bad.
> Midweek days are so-so.
> Fridays are better.
> Weekends are best.
> Weekends are best.
*/
How to Add Values to Enumerations
It is also possible to associate values to the enum constants, as you can see below in the Environment enum. When you invoke one of the enum constants, it will pass in the associated values to the enum constructor. For instance, when you invoke the Environment.PRODUCTION enum below, it will pass in the value api.codingnomads.co to the enum constructor, which in turn sets the enum's host variable to api.codingnomads.co. If/when you invoke the getHost() method on the enum, it will return api.codingnomads.co.
/* Enumeration to handle a deployment environment */
public enum Enviroment{
/* If someone uses Enviroment.PRODUCTION
the constructor below will be called
with "api.codingnomads.co" */
PRODUCTION("api.codingnomads.co"),
STAGING("staging.codingnomads.co"),
DEV("dev.codingnomads.co"),
LOCAL("localhost:8000");
private String host;
Enviroment(String host){
this.host = host;
}
public String getHost(){
return host;
}
}
The code above works wonders when you have a fixed set of constants that possess a set of associated traits. By using an enum, you are only required to define the constants and their associated traits once, and then you can access those constants and their associated traits as often as necessary.
How to Add Methods to Enumerations
In addition to possessing properties and a constructor, the following Planet enum (from the Java docs) incorporates methods for obtaining the surface gravity and weight of an object on each planet. Each enum constant is defined with specific values for the mass and radius parameters, which are then passed to the constructor during the constant's creation. It is essential in Java that enum constants be declared before any fields or methods, and when fields and methods are present, the enumeration constant list must conclude with a semicolon.
Below is an example program that takes your weight on Earth (in any unit), computes, and displays your weight on all the planets (in the same unit):
public enum Planet {
/* when Planet.MERCURY (for instance) it
will invoke the constructor below with
the parameter values provided */
MERCURY (3.303e+23, 2.4397e6),
VENUS (4.869e+24, 6.0518e6),
EARTH (5.976e+24, 6.37814e6),
MARS (6.421e+23, 3.3972e6),
JUPITER (1.9e+27, 7.1492e7),
SATURN (5.688e+26, 6.0268e7),
URANUS (8.686e+25, 2.5559e7),
NEPTUNE (1.024e+26, 2.4746e7);
private final double mass; /* in kilograms */
private final double radius; /* in meters */
Planet(double mass, double radius) {
this.mass = mass;
this.radius = radius;
}
private double mass() { return mass; }
private double radius() { return radius; }
/* universal gravitational constant (m3 kg-1 s-2) */
public static final double G = 6.67300E-11;
double surfaceGravity() {
return G * mass / (radius * radius);
}
double surfaceWeight(double otherMass) {
return otherMass * surfaceGravity();
}
public static void main(String[] args) {
if (args.length != 1) {
System.err.println("Usage: java Planet <earth_weight>");
System.exit(-1);
}
double earthWeight = Double.parseDouble(args[0]);
double mass = earthWeight/EARTH.surfaceGravity();
for (Planet p : Planet.values())
System.out.printf("Your weight on %s is %f%n",
p, p.surfaceWeight(mass));
}
}
If you run the Planet class with an argument of 175, you get this output:
Your weight on MERCURY is 66.107583
Your weight on VENUS is 158.374842
Your weight on EARTH is 175.000000
Your weight on MARS is 66.279007
Your weight on JUPITER is 442.847567
Your weight on SATURN is 186.552719
Your weight on URANUS is 158.397260
Your weight on NEPTUNE is 199.207413
This example comes from the Oracle docs.
Summary: What is a Java enum
- Enumerations are sets of related items. For example, "North", "South", "East", and "West".
- An enumeration is also referred to as an
enum - An
enumis a specific type in Java - similar to a class - Enums can be set with values and contain methods
Syntax
Here's the syntax for creating an enum in Java, where you can substitute the variables starting with your_ with your values and add as many parameters as you'd like.
public enum Your_Enum {
YOUR_EXAMPLE_VALUE_1,
YOUR_EXAMPLE_VALUE_2,
YOUR_EXAMPLE_VALUE_3;
}