Enums in Java

They are weird, literally

Basics

Declaring Enums

public enum Season {
    WINTER,
    SPRING,
    SUMMER,
    FALL
}

You can also declare them inside another class. You cannot declare an Enum inside a method body or constructor. It cannot have duplicate values

Usage

class Main {
    public enum Season {
        WINTER, SPRING, SUMMER, FALL
    }

    public static void main(String[] args) {
        System.out.println("-------");
        display(Season.WINTER);
        System.out.println("-------");
        enumIterate();
        System.out.println("-------");
        enumSwitchExample(Season.SUMMER);
        System.out.println(Season.FALL == Season.WINTER);
        System.out.println(Season.SPRING == Season.SPRING);
        System.out.println("-------");
    }

    public static void display(Season s) {
        System.out.println(s.name());
    }

    public static void enumIterate() {
        for (Season s : Season.values()) {
            System.out.println(s.name());
        }
    }

    public static void enumSwitchExample(Season s) {
        switch (s) {
            case WINTER:
                System.out.println("It's pretty cold");
                break;
            case SPRING:
                System.out.println("It's warming up");
                break;
            case SUMMER:
                System.out.println("It's pretty hot");
                break;
            case FALL:
                System.out.println("It's cooling down");
                break;
        }
    }
}

Enums with methods

Enum constants are technically mutable, so a setter could be added to change the internal structure of an enum constant. However, this is considered very bad practice and should be avoided. Best practice is to make

Enum fields immutable, with final :

EnumMap

EnumSet

Enum starting with number

Java does not allow the name of enum to start with number like 100A, 25K. In that case, we can append the code with _ (underscore) or any allowed pattern and make check of it.

Enum get very complicated

Last updated

Was this helpful?