When to use Java Enums

Yashod Perera
2 min readJan 27, 2022

--

Photo by Glenn Carstens-Peters on Unsplash

There are lots of jargons and technics to store constants in programming and enums are one of the method and let’s go through when to use these enums. We use enums when we satisfy following both conditions

  1. To define never changing values.
  2. To define collection of values.

As an example we can use collection of vehicle types as an Enum, or set of colors.

There are two ways of defining Enums in Java. One is the simple traditional way as follows.

public enum Vehicle {
MOTOCYCLE, CAR, VAN, JEEP;
}
public class Main {

public static void main(String[] args) {
// write your code here
Vehicle v = Vehicle.MOTOCYCLE;
System.out.println(v);
System.out.println();
// iterate the enum
for (Vehicle vehicle : Vehicle.values()) {
System.out.println(vehicle.name());
}
}
}

Results are as follows.

MOTOCYCLEMOTOCYCLE
CAR
VAN
JEEP

Other method is to use advanced method of writing it defining custom methods. We can define variable values for it we can get values as follows.

public enum Color {
RED("red"),
GREEN("green"),
BLUE("blue"),
YELLOW("yellow"),
GRAY("gray");

private String color;

Color(String color) {
this.color = color;
}

public String getColor() {
return color;
}
}
public class Main {

public static void main(String[] args) {
// write your code here
Color blue = Color.BLUE;
System.out.println(blue.name()); // Print Enum
System.out.println(blue.getColor()); // Invoke function
System.out.println();

for (Color color : Color.values()) {
System.out.println(color.getColor());
}
}
}

Results are as follows.

BLUE
blue
red
green
blue
yellow
gray

Hope you got a basic understanding of Enums in Java. If you have found this helpful please hit that 👏 and share it on social media :)

--

--

Yashod Perera

Technical Writer | Tech Enthusiast | Open source contributor