Shiklo Programming
EN
  • English
  • Español
  • Português
  • Deutsch
  • Français
  • 日本語
  • हिन्दी

Java Enums

Some values come from a small, fixed set: the days of the week, the sizes of a T-shirt, the states of a traffic light. You could store them as text or numbers, but then a typing mistake like "Wedensday" or a wrong number slips through unnoticed. An enum (enumeration) is a special class with a fixed list of named constants, so the compiler checks every value.

Declaring and using an enum

enum Size {
    SMALL, MEDIUM, LARGE
}

public class Main {
    public static void main(String[] args) {
        Size s = Size.MEDIUM;
        System.out.println(s);
        System.out.println(s == Size.MEDIUM);
        System.out.println(s.ordinal());
        System.out.println(s.name().toLowerCase());
    }
}
Output
MEDIUM
true
1
medium

The constants are written in capital letters. ordinal() gives the position (starting at 0), and name() the constant's name as text. Enums can be compared safely with ==.

Looping over the values

values() returns an array of all the constants, in order. valueOf turns text into a constant:

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

public class Main {
    public static void main(String[] args) {
        for (Day d : Day.values()) {
            System.out.print(d.name().substring(0, 3) + " ");
        }
        System.out.println();
        Day today = Day.valueOf("FRIDAY");
        System.out.println(today.ordinal() + 1);
    }
}
Output
MON TUE WED THU FRI SAT SUN 
5

If the text does not match any constant, valueOf throws an IllegalArgumentException.

Enums and switch

Enums work very well with switch. Inside the cases you write just the constant's name, and a switch expression over an enum needs no default when every constant is covered:

enum Light {
    RED, YELLOW, GREEN
}

public class Main {
    static String action(Light l) {
        return switch (l) {
            case RED -> "Stop";
            case YELLOW -> "Get ready";
            case GREEN -> "Go";
        };
    }

    public static void main(String[] args) {
        for (Light l : Light.values()) {
            System.out.println(l + ": " + action(l));
        }
    }
}
Output
RED: Stop
YELLOW: Get ready
GREEN: Go

If someone adds a new constant to Light later, this switch stops compiling until the new case is handled, which is exactly what you want.

Enums with fields and methods

An enum is a class, so its constants can carry data. Give the enum a field and a constructor, and write the values in brackets after each constant:

enum Planet {
    MERCURY(0.38), EARTH(1.0), MARS(0.38), JUPITER(2.53);

    private final double gravity;

    Planet(double gravity) {
        this.gravity = gravity;
    }

    double weightOf(double earthWeight) {
        return earthWeight * gravity;
    }
}

public class Main {
    public static void main(String[] args) {
        for (Planet p : Planet.values()) {
            System.out.printf("%-8s %6.1f kg%n", p, p.weightOf(60));
        }
    }
}
Output
MERCURY    22.8 kg
EARTH      60.0 kg
MARS       22.8 kg
JUPITER   151.8 kg

The constructor of an enum is always private: the only objects that will ever exist are the constants listed at the top.

Practice exercises

  1. Make an enum Season and print all seasons with their position.
  2. Write a switch expression that returns the typical temperature of each season.
  3. Give an enum Coin a field with its value in paise and print the total of an array of coins.