Skip to main content

Introduction to Enums

An enum (short for enumeration) in Java is a special data type that represents a fixed set of constants. It is essentially a special kind of class that always returns a predetermined number of instances.

Enums were introduced in Java 5 to solve a major issue with how constants were previously handled in Java.


Why do we need Enums?

Before Java 5, if you wanted to define a fixed set of constants (like the days of the week, or t-shirt sizes), you would typically use public static final int variables:

The "Old Way" (Integer Constants)

public class OldSizes {

public static final int SMALL = 1;
public static final int MEDIUM = 2;
public static final int LARGE = 3;
}

The problem with this approach is Type Safety. If a method expects a size, it has to accept an int. But what stops a developer from passing 99 or -5 to that method? Nothing. The compiler only knows it's an integer; it doesn't know it's supposed to be restricted to 1, 2, or 3.

The "Modern Way" (Enums)

Enums completely solve this type safety issue. When you create an enum, you are creating a brand new, strongly-typed classification.

public enum Size {
SMALL,
MEDIUM,
LARGE,
}

Now, if a method expects a Size, you must pass one of the predefined constants. The compiler will literally not allow you to pass anything else!


Defining and Using an Enum

An enum can be defined inside a class, or in its own separate file (just like a normal class). By convention, enum constants are written in ALL_CAPS.

// Defining an enum outside the main class
enum Level {
LOW,
MEDIUM,
HIGH,
}

public class LabEnum1 {

public static void main(String[] args) {
// Assigning an enum constant to a variable
Level myLevel = Level.MEDIUM;

System.out.println("The selected level is: " + myLevel);
}
}

[!NOTE] Under the hood, Java automatically creates a class that extends java.lang.Enum for your enum. Because Java does not support multiple inheritance, an enum cannot extend any other class. However, it can implement interfaces!