Codectionary / Developer documentation / Java

Enums

An enum (enumeration) is a special Java type used to define a fixed set of named constants, like the days of the week or possible states of an order. Enums are type-safe - the compiler ensures only valid enum values can be assigned - and, unlike simple constants, they are full classes that can have fields, constructors, and methods of their own.

Syntax

enum EnumName {\n  CONSTANT_1, CONSTANT_2\n}

Examples

Basic Enum

Defining and using a simple set of named constants.

public enum Day {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}

public class EnumExample {
    public static void main(String[] args) {
        Day today = Day.WEDNESDAY;

        if (today == Day.SATURDAY || today == Day.SUNDAY) {
            System.out.println("Weekend!");
        } else {
            System.out.println("Weekday");
        }
    }
}

Enum with switch

Enums integrate naturally with switch statements.

enum TrafficLight { RED, YELLOW, GREEN }

public static String getAction(TrafficLight light) {
    switch (light) {
        case RED:
            return "Stop";
        case YELLOW:
            return "Slow down";
        case GREEN:
            return "Go";
        default:
            return "Unknown";
    }
}

System.out.println(getAction(TrafficLight.GREEN));  // Go

Enum with Fields and Constructors

Enums can carry their own data, since each constant is actually an object.

public enum Planet {
    MERCURY(3.3e23, 2.4e6),
    EARTH(5.97e24, 6.4e6),
    MARS(6.4e23, 3.4e6);

    private final double mass;   // kg
    private final double radius; // meters

    Planet(double mass, double radius) {
        this.mass = mass;
        this.radius = radius;
    }

    public double surfaceGravity() {
        final double G = 6.67300E-11;
        return G * mass / (radius * radius);
    }
}

System.out.printf("Earth gravity: %.2f%n", Planet.EARTH.surfaceGravity());

Useful Enum Methods

Built-in methods every enum automatically gets: values(), name(), and ordinal().

enum Size { SMALL, MEDIUM, LARGE }

for (Size s : Size.values()) {  // iterate over every constant
    System.out.println(s.name() + " = " + s.ordinal());
}
// SMALL = 0
// MEDIUM = 1
// LARGE = 2

Size chosen = Size.valueOf("MEDIUM");  // parse from a String
System.out.println(chosen);

Best practices

  • Use enums instead of plain int or String constants whenever a variable should only take one of a fixed, known set of values - it gives you compile-time safety
  • Take advantage of switch statements with enums for exhaustive, readable branching on the possible values
  • Add fields and methods to an enum when each constant needs associated data, rather than maintaining a separate lookup table
  • Use ALL_CAPS naming for enum constants, following the same convention as other constants in Java

At a glance

Purpose
General-purpose application development
File extension
.java
Runs in
Java Virtual Machine
Usually used with
JDK and Java libraries

Specifications & further reading

Related Java documentation

Classes
Classes in Java are blueprints for creating objects, defining their properties (fields) and behaviors (methods). Java is a strictly object-oriented language where everything is encapsulated within classes. A class serves as a template that specifies what data an object will store and what operations it can perform.
Interfaces
An interface defines a contract of methods that implementing classes must provide, without specifying how those methods work internally. Unlike a class, an interface cannot be instantiated directly - it only declares what a class can do, not how. A class uses the 'implements' keyword to fulfill an interface's contract, and a single class can implement multiple interfaces, which is Java's way of achieving a form of multiple inheritance.
Abstract Classes
An abstract class is a class that cannot be instantiated directly and may contain both fully implemented methods and abstract methods (declared without a body, which subclasses must implement). Abstract classes sit between interfaces and regular classes: like an interface, they define a contract; like a regular class, they can hold state (fields) and provide shared, already-implemented behavior.
Constructors
A constructor is a special method that runs automatically when an object is created with 'new', typically used to initialize the object's fields. A constructor shares its name with the class and has no return type, not even void. Java supports constructor overloading, letting a class offer multiple ways to construct an object, and constructor chaining with this(...), where one constructor calls another in the same class.