Skip to lesson

An enum is a type with a fixed set of named values, like the classes on a train ticket or the steps of a food order. Java then checks that a variable of that type holds only one of those values.

The problem with int and String constants

Type safety means the compiler checks that every value has the right type, so a wrong value becomes a compile error instead of a bug that shows up while the program runs.

A train ticket is Sleeper, AC 3 Tier or AC 2 Tier. Before enums, programs stored such values as static final int constants (opens in a new tab) or plain Strings. Both accept wrong values without any error.

Example 1 · Problem: an int accepts any number

IntConstantsDemo.javaJava
public class IntConstantsDemo {    static final int SLEEPER = 1;    static final int AC_3_TIER = 2;    static final int AC_2_TIER = 3;
    static String className(int travelClass) {        if (travelClass == SLEEPER) {            return "Sleeper";        } else if (travelClass == AC_3_TIER) {            return "AC 3 Tier";        } else if (travelClass == AC_2_TIER) {            return "AC 2 Tier";        }        return "Unknown";    }
    public static void main(String[] args) {        int priyaClass = AC_3_TIER;        int rohanClass = 7;        System.out.println("Priya: " + className(priyaClass));        System.out.println("Rohan: " + className(rohanClass));        System.out.println("Saved value: " + priyaClass);    }}
Output
Priya: AC 3 Tier
Rohan: Unknown
Saved value: 2

What this code does

  • rohanClass is just an int, so 7 compiles even though no class 7 exists. The bug shows up only when someone reads Unknown.
  • Printing priyaClass shows 2. A reader must look up what 2 means.

Example 2 · Problem: a typo in a String, and no error

StringStatusDemo.javaJava
public class StringStatusDemo {    static void notifyCustomer(String status) {        if (status.equals("DELIVERED")) {            System.out.println("Your order has arrived.");        } else if (status.equals("SHIPPED")) {            System.out.println("Your order is on the way.");        } else {            System.out.println("Your order is being prepared.");        }    }
    public static void main(String[] args) {        notifyCustomer("SHIPPED");        notifyCustomer("Delivered");        notifyCustomer("DELIVERD");    }}
Output
Your order is on the way.
Your order is being prepared.
Your order is being prepared.

What this code does

  • "Delivered" (wrong case) and "DELIVERD" (typo) are valid Strings, so the program compiles and runs.
  • Two customers get the wrong message, and nothing warns the developer. This is the kind of bug an enum removes.

Four problems come from this:

  • Any value fits. An int variable accepts 7, though there is no class 7.
  • Typos compile. "DELIVERD" is still a valid String, so the mistake shows up only as wrong behaviour.
  • Swapped arguments compile. A class code and a berth code are both int, so Java cannot tell them apart.
  • Unclear output. Printing the variable shows 2, not the name of the class.

An enum: a type with a fixed set of values

An enum (short for enumeration) is a special class that defines a fixed set of named constants, such as enum Signal { RED, YELLOW, GREEN }. A variable of an enum type can hold only one of those constants, or null.

Write the keyword enum, a name, and the values inside braces. TrainClass is then a type, like String, and the compiler accepts only its listed values.

Syntax
enum EnumName { CONSTANT_1, CONSTANT_2, CONSTANT_3 }

Example 3 · The fix: an enum for the ticket class

EnumTicketDemo.javaJava
enum TrainClass {    SLEEPER, AC_3_TIER, AC_2_TIER, AC_FIRST}
public class EnumTicketDemo {    static void printTicket(String passenger, TrainClass travelClass, int fare) {        System.out.println(passenger + " | " + travelClass + " | Rs. " + fare);    }
    public static void main(String[] args) {        printTicket("Priya", TrainClass.AC_3_TIER, 1450);        printTicket("Rohan", TrainClass.SLEEPER, 545);        TrainClass upgrade = TrainClass.AC_2_TIER;        printTicket("Kavya", upgrade, 2090);    }}
Output
Priya | AC_3_TIER | Rs. 1450
Rohan | SLEEPER | Rs. 545
Kavya | AC_2_TIER | Rs. 2090

What this code does

  • TrainClass is used as a parameter type and a variable type. You reach a constant through the enum name and a dot: TrainClass.SLEEPER.
  • Printing a constant prints its name, so the ticket is readable without a lookup table.

Example 4 · The compiler now stops wrong values

WrongValueDemo.javaJava
enum TrainClass {    SLEEPER, AC_3_TIER, AC_2_TIER, AC_FIRST}
public class WrongValueDemo {    public static void main(String[] args) {        TrainClass a = TrainClass.AC_3_TIER;        TrainClass b = 7;        TrainClass c = "SLEEPER";        TrainClass d = TrainClass.SLEEPR;        System.out.println(a);    }}
Sample compiler output
WrongValueDemo.java:8: error: incompatible types: int cannot be converted to TrainClass
        TrainClass b = 7;
                       ^
WrongValueDemo.java:9: error: incompatible types: String cannot be converted to TrainClass
        TrainClass c = "SLEEPER";
                       ^
WrongValueDemo.java:10: error: cannot find symbol
        TrainClass d = TrainClass.SLEEPR;
                                 ^
  symbol:   variable SLEEPR
  location: class TrainClass
3 errors

What this code does

  • The three bugs of the old way are now compile errors: a number, a String, and a typo in the constant name.
  • Each error points at the exact line, before the program ever runs. That is type safety.

Constant names use UPPER_CASE with underscores, like other constants. An enum can sit above your class in the same file without public (as in these lessons), in its own file as public enum TrainClass in TrainClass.java, or inside a class as a nested enum, used as Order.Status.PLACED.

Each enum constant is one object

An enum constant is one named value of an enum, such as TrainClass.SLEEPER. Java creates it as a single object of the enum, once, and it behaves like a public static final field that can never point to another object.

Java creates the constant objects itself, once, when the enum is first used. You cannot create more with new, so every variable that holds TrainClass.SLEEPER points to the same object.

The enum TrainClass has exactly three objects on the heap: SLEEPER, AC_3_TIER and AC_2_TIER. The variables a and b both point to the one SLEEPER object, so a == b is true. new TrainClass() is crossed out: no more objects can be made.

Example 5 · One object per constant, compared with ==

SameObjectDemo.javaJava
enum TrainClass {    SLEEPER, AC_3_TIER, AC_2_TIER}
public class SameObjectDemo {    public static void main(String[] args) {        TrainClass a = TrainClass.SLEEPER;        TrainClass b = TrainClass.SLEEPER;        TrainClass notChosen = null;        System.out.println(a == b);        System.out.println(a == TrainClass.AC_3_TIER);        System.out.println(notChosen == TrainClass.SLEEPER);    }}
Output
true
false
false

What this code does

  • a and b hold the same SLEEPER object, so a == b is true. No copy of a constant is ever made.
  • notChosen is null. == simply answers false; notChosen.equals(...) would have thrown NullPointerException.

So the right way to compare enum values is ==. equals() gives the same answer, but == has two extra safety checks: null == TrainClass.SLEEPER is just false, while calling .equals() on null throws NullPointerException. And == between two different enum types, such as a Day and a Month, is a compile error: incomparable types: Day and Month.

With Strings, == is a bug, as in equals() vs == (opens in a new tab). With enum constants it is correct, because each constant exists only once.

When to use an enum

Use an enum when you can write the complete list today and it changes only with an app update: days, order status, payment mode, seat class. An enum also works as a field type, so an object can store its state safely.

Example 6 · An enum as a field: an order and its status

OrderFieldDemo.javaJava
enum OrderStatus {    PLACED, SHIPPED, DELIVERED, CANCELLED}
class Order {    private final int id;    private OrderStatus status = OrderStatus.PLACED;
    Order(int id) {        this.id = id;    }
    void ship() {        if (status == OrderStatus.PLACED) {            status = OrderStatus.SHIPPED;        }    }
    void cancel() {        if (status == OrderStatus.PLACED) {            status = OrderStatus.CANCELLED;            System.out.println("Order " + id + " cancelled");        } else {            System.out.println("Order " + id + " cannot be cancelled: " + status);        }    }}
public class OrderFieldDemo {    public static void main(String[] args) {        Order first = new Order(101);        Order second = new Order(102);        second.ship();        first.cancel();        second.cancel();    }}
Output
Order 101 cancelled
Order 102 cannot be cancelled: SHIPPED

What this code does

  • status is a private field of type OrderStatus. It starts at PLACED; without that starting value it would be null, like any object field.
  • The field can only ever hold one of the four statuses, so cancel() needs no check for a misspelt status.

Do not use an enum for values that users add while the app runs, such as city names, student names or product prices: those belong in objects of a normal class. A single fixed number, like MAX_SEATS = 72, stays a static final constant (opens in a new tab).

Quick test: if adding a new value means changing the code anyway, an enum fits.

Next step

Check your understanding

12 quick questions