๐ŸŽ“ A1Learner
๐Ÿ”
0 of 48 lessons completed

Java Enums

An enum is a type that holds a fixed set of named values. A variable of an enum type can hold only one of those values at a time.

A variable holds one constant

The Level enum names three constants. The variable holds the MEDIUM constant.

public class Main {
  public static void main(String[] args) {
    Level level = Level.MEDIUM;
    System.out.println(level);
  }
}
enum Level {
  LOW, MEDIUM, HIGH
}

A switch over an enum

The switch tests the enum value. The HIGH case prints its line.

public class Main {
  public static void main(String[] args) {
    Level level = Level.HIGH;
    switch (level) {
      case LOW:
        System.out.println("Low level");
        break;
      case MEDIUM:
        System.out.println("Medium level");
        break;
      case HIGH:
        System.out.println("High level");
        break;
    }
  }
}
enum Level {
  LOW, MEDIUM, HIGH
}

All constants in order

The values method returns every constant of the enum. The loop prints one constant per line.

public class Main {
  public static void main(String[] args) {
    for (Level level : Level.values()) {
      System.out.println(level);
    }
  }
}
enum Level {
  LOW, MEDIUM, HIGH
}

Example

public class Main {
  public static void main(String[] args) {
    Size size = Size.LARGE;
    System.out.println(size);
    switch (size) {
      case SMALL:
        System.out.println("Small cup");
        break;
      case MEDIUM:
        System.out.println("Medium cup");
        break;
      case LARGE:
        System.out.println("Large cup");
        break;
    }
  }
}
enum Size {
  SMALL, MEDIUM, LARGE
}

Key points

  • The enum keyword starts an enum.
  • Each named value in an enum is a constant.
  • Enum constants are written in uppercase letters.
  • A variable of an enum type holds one of the constants.
  • A switch statement can test an enum value.
  • The values method returns all the constants in order.

In this example, the Size enum names three cup sizes. The size variable holds the LARGE constant. The first print line shows the constant name. The switch then matches the LARGE case and prints its line.

Note

Printing an enum value prints the name of the constant.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does Level.values() return?