Skip to content
Tutorials Center
My learning

Topics

Lesson 62 of 201 ยท Object-Oriented Programming

Enums

Learn Java enums - named constants, values() and valueOf, fields and constructors, constant-specific methods, switch expressions, EnumSet and EnumMap.

Some types have a fixed, known set of values: the days of the week, the suits in a deck of cards, the states of an order (PENDING, PAID, SHIPPED, DELIVERED). Before Java 5, programmers represented them with int constants like static final int PAID = 1;. Nothing stopped anyone from passing 42 where a status was expected, and printing a status showed a meaningless number.

An enum (short for enumeration) is a type whose only possible values are the constants you list. The compiler rejects anything else, each constant knows its own name, and because enums are real classes, each constant can carry data and behavior. This lesson covers declaring and using enums, the built-in methods, fields and constructors, constants with their own method bodies, enums in switch, a preview of EnumSet and EnumMap, and the mistakes to avoid.

Declaring and using an enum

Java
enum Direction { NORTH, EAST, SOUTH, WEST }

Direction is now a type, and Direction.NORTH through Direction.WEST are its only values (plus null, as for any reference type). Constants are written in UPPER_SNAKE_CASE by convention.

Java Enum basics and built-in methods

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The methods every enum gets for free:

Method What it does
values() A new array of all constants, in declaration order.
valueOf(String) The constant with exactly that name; throws IllegalArgumentException otherwise.
name() The constant's name as written in the source, like "EAST". Final, can't be overridden.
toString() Returns name() by default, but you may override it for display text.
ordinal() The position in the declaration, starting at 0.
compareTo(other) Compares by ordinal; enums are Comparable.
equals, hashCode Identity-based, which is correct because each constant exists exactly once.

Because each constant is a single object created when the enum class loads, comparing enums with == is safe and preferred. == can't throw a NullPointerException when the left side is null, and the compiler complains if you compare constants of two different enum types.

The last line shows No enum constant Main.Direction.south. valueOf is case-sensitive and strict. When parsing user input, normalize first (Direction.valueOf(text.strip().toUpperCase())) and catch the exception, or search values() for a match.

Enums in switch

Enums and switch belong together. Inside a switch on an enum, you write constants without the type name. A switch expression that covers every constant needs no default branch: the compiler checks that it's exhaustive.

Java A switch expression over every constant

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Exhaustiveness is a real safety feature. If someone later adds NORTHEAST to the enum, both switch expressions stop compiling with the switch expression does not cover all possible input values, pointing at every place that needs updating. A default branch would silently hide those places, so leave it out when you've handled every constant. (switch Statements and Expressions covers the syntax in detail.)

Fields, constructors and methods

An enum is a class, so it can have fields, a constructor and methods. Each constant passes arguments to the constructor in parentheses. The list of constants must come first and end with a semicolon when anything follows it:

Java An enum with data, methods and a lookup

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Some details worth knowing:

  • Enum constructors are always private. You can't write new CupSize(...); the constants are the only instances that will ever exist. Writing public on the constructor is a compile error.
  • Fields should be final. Constants are shared by the whole program, so mutable state in an enum is effectively global mutable state. Avoid it.
  • Lookups by a field are best built once in a static map, as fromCode does. A static initializer runs after all constants are created, so values() is ready there. (An enum constructor, on the other hand, can't access the enum's static fields; that's a compile error, because they aren't initialized yet.)

Constant-specific behavior

Sometimes each constant needs a different implementation of a method. Declare the method abstract in the enum and give each constant its own body in braces. Each constant then becomes an instance of its own anonymous subclass:

Java Each constant with its own method body

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The abstract method guarantees every constant supplies a cost; a new constant without one won't compile. Notice the last two lines: a constant with a body is an instance of an anonymous class (Main$Shipping$2), so getClass() doesn't return the enum class. Use getDeclaringClass() when you need the enum type itself.

An alternative is to pass a lambda to the constructor (for example a DoubleUnaryOperator field). Constant bodies read better when the logic is longer than one expression; lambdas when it's a single formula. A third option is a switch over this inside a regular method, which keeps all cases in one place.

Enums implementing interfaces

Enums can't extend a class (they already extend java.lang.Enum), but they can implement interfaces. That lets enum constants sit next to ordinary classes behind a common type:

Java
interface Priced {
    double price();
}

enum Topping implements Priced {
    CHEESE(1.00), MUSHROOMS(0.80), OLIVES(0.60);

    private final double price;

    Topping(double price) {
        this.price = price;
    }

    @Override
    public double price() {
        return price;
    }
}

An enum with a single constant is also the simplest correct way to write a singleton in Java (enum AppConfig { INSTANCE; ... }). The JVM guarantees exactly one instance, even with serialization and reflection. Creational Design Patterns compares it with other approaches.

EnumSet and EnumMap

The JDK has two collections designed for enums. They are faster and more compact than HashSet and HashMap, because internally they work with the constants' ordinals:

  • EnumSet stores a set of constants as bits, perfect for flags and options.
  • EnumMap is a map whose keys are constants, stored in an array in declaration order.
Java EnumSet for flags, EnumMap for counts

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

EnumMap prints its keys in declaration order, not hash order, and CANCELLED is missing because no order had that status. EnumMap, EnumSet, IdentityHashMap, WeakHashMap and BitSet goes further.

Common mistakes

  • Storing ordinal() in a database or file. Inserting a new constant in the middle shifts every ordinal after it, and old data now means something else. Store name() (or a dedicated code field) instead.
  • Relying on toString() for parsing. If you override toString for display, valueOf(toString()) stops working. Parse with name() or a lookup method.
  • Forgetting that values() copies the array. It allocates a new array on every call. In hot code, cache it in a private static final field.
  • Using a default branch in exhaustive switch expressions, which hides missing cases when constants are added.
  • Putting mutable state in constants. It's shared everywhere, including across threads.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Given enum Level { LOW, MEDIUM, HIGH }, what does Level.HIGH.ordinal() + " " + Level.valueOf("LOW") produce?

    Ordinals start at 0, so HIGH is 2. valueOf("LOW") returns the LOW constant, whose toString is its name.
  2. 2. What happens when you call Level.valueOf("high")?

    valueOf matches the exact constant name. Normalize input first, for example with toUpperCase(), and handle the exception.
  3. 3. Why can a switch expression over all constants of an enum omit default?

    For enums, covering every constant makes the switch expression exhaustive. If a constant is added later, the code stops compiling, which shows you every place to update.
  4. 4. Which is true about enum constructors?

    Enum constructors are implicitly private. The constants in the declaration are the only instances that will ever exist.
  5. 5. You need to save an order's status in a database. What should you store?

    Ordinals change when constants are reordered or inserted, and hash codes are not stable between runs. The name (or an explicit code) stays meaningful.

Summary

  • An enum defines a type whose values are a fixed list of named constants; compare them with ==.
  • Every enum has values(), valueOf(String) (case-sensitive, throws on unknown names), name(), ordinal(), toString() and compareTo.
  • Switch expressions over enums can be exhaustive without default, so adding a constant reveals every switch to update.
  • Enums can have final fields, private constructors, methods, static lookup maps and interfaces they implement.
  • Declare an abstract method to give each constant its own body; such constants are anonymous subclasses, so use getDeclaringClass() to get the enum type.
  • EnumSet and EnumMap are fast, ordered collections for enum values. Store names, not ordinals.

Next: Nested, Inner, Local and Anonymous Classes, where you'll learn the four ways to declare a class inside another class or method.