AI Hints
Home›Java Tutorial›Interfaces, Records and Enums
Java · Lesson 81 of 120

Enums

A fixed set of values.

⏱ 2 min read▶ Video at 1:42:24🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

Some things only have a few possible values. Days of the week, card suits, or coffee sizes. An enum lists them all, so nothing else can sneak in.

  • A few possible values
  • Listed once
  • Nothing else allowed

Size.java

Enum Size has exactly three values, written in capitals. Each one can carry data, here a price. And enums can have fields, constructors, and methods, like a class.

Main.javajava
public enum Size {
    SMALL(2.50), MEDIUM(3.00), LARGE(3.50);

    private final double price;
    Size(double price) { this.price = price; }
    public double price() { return price; }
}

Using an enum

Size dot medium is one of the values. Values gives all of them, in order. Switch works beautifully with enums. With all three covered, no default is needed. Ordinal gives the position, and value of turns text into an enum. Run it. Medium costs three. Then each size with its position. And large costs three fifty.

Main.javajava
public class Main {
    public static void main(String[] args) {
        Size s = Size.MEDIUM;
        System.out.println(s + " costs " + s.price());
        for (Size size : Size.values()) {
            String label = switch (size) {
                case SMALL -> "a small cup";
                case MEDIUM -> "a medium cup";
                case LARGE -> "a big cup";
            };
            System.out.println(size.ordinal() + ": " + label);
        }
        System.out.println(Size.valueOf("LARGE").price());
    }
}
Output
MEDIUM costs 3.0
0: a small cup
1: a medium cup
2: a big cup
3.5
Also uses Size.java
public enum Size {
    SMALL(2.50), MEDIUM(3.00), LARGE(3.50);

    private final double price;
    Size(double price) { this.price = price; }
    public double price() { return price; }
}

What module nine taught

Encapsulation hides data behind methods. Inheritance builds on a parent, with extends and super. Overriding and polymorphism let each object act in its own way. Abstract classes, and interfaces, describe what children must do. And records and enums are handy special classes.

keyvalue
Hideprivate + methods
Reuseextends, super
Many forms@Override, polymorphism
Specialinterface, record, enum

Summary

An enum is a fixed set of named values, that can carry data. That's the end of module nine. Next module, collections.

Key takeaways
  • enum Size { … }
  • values(), valueOf()
  • switch on enums
Next up: ArrayList — a list that grows