← Back to Core Java Course | Chapter 13: Advanced Topics & Reference | Lesson 4 of 10

Java Enum

What is an Enum?

An enum defines a fixed, named set of constant values, like DAY or SUIT, giving you compile-time safety that a variable can only ever hold one of those specific values. Because the compiler restricts a variable of this enum type to only its declared constants, invalid values become impossible rather than just discouraged.

Example: What is an Enum?

java
enum Day { MONDAY, TUESDAY, WEDNESDAY }
public class Main {
	public static void main(String[] args) {
		Day today = Day.MONDAY;
		System.out.println(today);
	}
}

Enum with Fields and Methods

Enum constants can carry their own fields and methods, letting each constant hold associated data (like a planet's mass) and expose behavior specific to that constant. This turns an enum into more than just a labeled constant, effectively giving each value its own mini-object with real behavior.

Example: Enum with Fields and Methods

java
enum Planet {
	EARTH(5.97), MARS(0.64);
	final double massInYottagrams;
	Planet(double mass) { this.massInYottagrams = mass; }
}
public class Main {
	public static void main(String[] args) {
		System.out.println(Planet.EARTH.massInYottagrams);
	}
}

Iterating over Enums

You can iterate every constant in an enum with EnumType.values(), which returns them as an array in the order they were declared. This is especially useful when you need to populate a dropdown, generate a report, or loop through every possible state a variable could hold.

Example: Iterating over Enums

java
enum Day { MONDAY, TUESDAY, WEDNESDAY }
public class Main {
	public static void main(String[] args) {
		for (Day d : Day.values()) {
			System.out.println(d);
		}
	}
}

Enum valueOf and ordinal

valueOf(String) converts a matching string back into its enum constant, throwing IllegalArgumentException if there's no match; ordinal() returns each constant's zero-based declaration position.

Example: Enum valueOf and ordinal

java
enum Day { MONDAY, TUESDAY, WEDNESDAY }
public class Main {
	public static void main(String[] args) {
		Day d = Day.valueOf("TUESDAY");
		System.out.println(d.ordinal()); // 1: zero-based position
	}
}

EnumSet and EnumMap

EnumSet and EnumMap are highly optimized collection implementations built specifically for enum keys, offering better performance than a generic HashSet/HashMap would for the same data.

Example: EnumSet and EnumMap

java
import java.util.EnumSet;
enum Day { MONDAY, TUESDAY, WEDNESDAY }
public class Main {
	public static void main(String[] args) {
		EnumSet<Day> weekStart = EnumSet.of(Day.MONDAY, Day.TUESDAY);
		System.out.println(weekStart);
	}
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.