🧱 Java Object-Oriented Programming
Estimated reading: 4 minutes 290 views

🎌 Java Enums Explained – Syntax, Examples, EnumSet & EnumMap


Introduction – Why Java Enums Matter

Imagine you’re building a game and need to define player levels: EASY, MEDIUM, HARD. You could use strings or integers β€” but what if someone accidentally sets level to β€œHARDD”? That’s where Java Enums shine.

Enums in Java provide a type-safe way to define a fixed set of constants. They are more powerful than enums in many other languages β€” because Java enums are full-fledged classes.

By the end of this article, you’ll understand:

What enums are and how to define them
How to add fields, methods, and constructors to enums
Enum best practices and real-world examples
EnumSet, EnumMap, and advanced use cases


What is an Enum in Java?

🎌 An enum (short for “enumeration”) is a special Java type used to define a set of predefined constants.

Java enums:

  • Are type-safe
  • Can have fields, methods, and constructors
  • Can implement interfaces

Basic Enum Syntax

enum Level {
    EASY,
    MEDIUM,
    HARD
}
public class TestEnum {
    public static void main(String[] args) {
        Level level = Level.MEDIUM;
        System.out.println("Selected level: " + level);
    }
}

Output:

Selected level: MEDIUM

Explanation:

  • Level is an enum with 3 constants.
  • Each constant (EASY, MEDIUM, HARD) is an object of Level.

Enum with Fields and Methods

enum Planet {
    MERCURY(3.30), VENUS(4.87), EARTH(5.97);

    private double mass; // in 10^24 kg

    Planet(double mass) {
        this.mass = mass;
    }

    public double getMass() {
        return mass;
    }
}
public class TestPlanet {
    public static void main(String[] args) {
        for (Planet p : Planet.values()) {
            System.out.println(p + " mass = " + p.getMass());
        }
    }
}

Explanation:

  • Each enum constant can hold associated data
  • Enums can have constructors and methods
  • Planet.values() returns an array of all enum constants

Common Enum Methods

MethodDescription
values()Returns array of all enum constants
ordinal()Returns the index of the constant (starts at 0)
name()Returns the name of the constant as a string
valueOf("NAME")Returns the enum constant by name

Enum in Switch Statement

enum Day { MONDAY, TUESDAY, FRIDAY }

public class TestDay {
    public static void main(String[] args) {
        Day d = Day.FRIDAY;

        switch (d) {
            case MONDAY:
                System.out.println("Start of week");
                break;
            case FRIDAY:
                System.out.println("Weekend incoming!");
                break;
            default:
                System.out.println("Midweek");
        }
    }
}

Enums work seamlessly with switch β€” providing clarity and readability


EnumSet and EnumMap

EnumSet Example

import java.util.EnumSet;

enum Direction { NORTH, EAST, SOUTH, WEST }

public class TestSet {
    public static void main(String[] args) {
        EnumSet<Direction> directions = EnumSet.of(Direction.NORTH, Direction.EAST);
        System.out.println(directions);
    }
}

EnumMap Example

import java.util.*;

enum Status { NEW, IN_PROGRESS, COMPLETED }

public class TestMap {
    public static void main(String[] args) {
        EnumMap<Status, String> statusMap = new EnumMap<>(Status.class);
        statusMap.put(Status.NEW, "Task Created");
        statusMap.put(Status.COMPLETED, "Task Done");

        System.out.println(statusMap);
    }
}

Note:

  • EnumSet is a highly efficient Set for enum types.
  • EnumMap is a specialized Map with enums as keys.

Best Practices for Java Enums

Use enums instead of int or String constants for clarity and safety
Use EnumSet or EnumMap for collections involving enums
Prefer switch-case for enum-driven logic
Group related values and logic inside the enum itself
Don’t abuse enums for unrelated constants β€” use only when values are logically grouped


Summary

  • Java enums are powerful and type-safe tools for defining constant values
  • They support fields, methods, constructors, and even interfaces
  • Used with switch, EnumSet, and EnumMap for clean, efficient logic
  • Enums improve code readability, safety, and maintainability

FAQs – Java Enums

Can Java enums have constructors?

Yes. Enum constructors are used to set fields for each constant, but they are private by default.

Can enums implement interfaces?

Yes. Enums can implement interfaces (but cannot extend classes).

What is the default type of Java enum constants?

Each enum constant is an instance of the enum class.

Can enum constants override methods?

Yes. Each constant can have its own implementation of a method using constant-specific class bodies.

Is enum a class in Java?

Yes. Under the hood, each enum is compiled into a class that extends java.lang.Enum.


Share Now :
Share

Java Enums

Or Copy Link

CONTENTS
Scroll to Top