Java Enums

Java Enums (Enumerations)

An enum is a special "class" that represents a group of constants (unchangeable variables, like final variables).

To create an enum, use the enum keyword (instead of class or interface), and separate the constants with a comma. They should be in uppercase letters.

Simple Enum Example

enum Level {
  LOW,
  MEDIUM,
  HIGH
}

public class Main { public static void main(String[] args) { Level myVar = Level.MEDIUM; System.out.println(myVar); } }


Why and When To Use Enums?

Use enums when you have values that you know aren't going to change, like month days, days of the week, colors, deck of cards, etc.

Enums provide type-safety. For example, if you have a method that accepts a Level, you can be sure that it will only be called with one of the predefined constants (LOW, MEDIUM, or HIGH). You can't accidentally pass an invalid String like "Urgent".


Enums in a switch Statement

Enums are often used in switch statements to check for corresponding values.

Enum in a Switch

enum Level {
  LOW,
  MEDIUM,
  HIGH
}

public class Main { public static void main(String[] args) { Level myVar = Level.MEDIUM; switch(myVar) { 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 Methods

An enum is a special type of class, and it can have attributes and methods. The only difference is that enum constants are public, static and final (unchangeable - cannot be overridden).

The values() method returns an array containing all the constants of the enum. The ordinal() method returns the index of the enum constant (starting from 0).

Looping Through an Enum

for (Level s : Level.values()) {
  System.out.println(s);
}