Java Enums

An enum is a special class for a fixed set of constants, like days of the week, order status or sizes. It is safer than plain numbers or strings, because the compiler checks the values.

Create and use an enum

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

public class Main {
    public static void main(String[] args) {
        Day today = Day.WEDNESDAY;
        System.out.println(today);
        System.out.println(today.name());
        System.out.println(today.ordinal());           // position, starts at 0
        System.out.println(Day.valueOf("FRIDAY"));

        for (Day d : Day.values()) {                   // all the constants
            System.out.print(d + " ");
        }
        System.out.println();
    }
}
Output

WEDNESDAY
WEDNESDAY
2
FRIDAY
MONDAY TUESDAY WEDNESDAY THURSDAY FRIDAY SATURDAY SUNDAY

Enum in switch

enum Level { LOW, MEDIUM, HIGH }

public class Sw {
    public static void main(String[] args) {
        Level level = Level.HIGH;
        String message = switch (level) {
            case LOW -> "All fine";
            case MEDIUM -> "Be careful";
            case HIGH -> "Danger";
        };
        System.out.println(message);
    }
}
Output

Danger

When you use all the constants, a switch expression needs no default. If you add a new constant later, the compiler shows an error in every switch you must update.

Enum with fields, a constructor and methods

enum Size {
    SMALL(10), MEDIUM(20), LARGE(30);

    private final int price;

    Size(int price) {                  // constructor is always private
        this.price = price;
    }

    int getPrice() {
        return price;
    }
}

public class Fields {
    public static void main(String[] args) {
        for (Size s : Size.values()) {
            System.out.println(s + " costs " + s.getPrice());
        }
        System.out.println(Size.LARGE.compareTo(Size.SMALL));
    }
}
Output

SMALL costs 10
MEDIUM costs 20
LARGE costs 30
2

Enum with an abstract method

enum Operation {
    ADD {
        int apply(int a, int b) { return a + b; }
    },
    MULTIPLY {
        int apply(int a, int b) { return a * b; }
    };

    abstract int apply(int a, int b);
}

public class Abs {
    public static void main(String[] args) {
        System.out.println(Operation.ADD.apply(3, 4));
        System.out.println(Operation.MULTIPLY.apply(3, 4));
    }
}
Output

7
12

EnumMap and EnumSet

import java.util.EnumMap;
import java.util.EnumSet;

enum Color { RED, GREEN, BLUE }

public class Maps {
    public static void main(String[] args) {
        EnumMap<Color, Integer> stock = new EnumMap<>(Color.class);
        stock.put(Color.BLUE, 5);
        stock.put(Color.RED, 12);
        System.out.println(stock);                    // in the order of the enum

        EnumSet<Color> warm = EnumSet.of(Color.RED);
        System.out.println(warm);
        System.out.println(EnumSet.complementOf(warm));
    }
}
Output

{RED=12, BLUE=5}
[RED]
[GREEN, BLUE]

Facts

  • Enums are classes. They can implement interfaces, but can not extend a class.
  • The constants are objects, created once. You can compare them with ==.
  • valueOf() throws an exception when the name does not exist.
Note: Use an enum whenever a variable can have only a small, known set of values. Next: Java Records.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.