🧱 Java Object-Oriented Programming
Estimated reading: 4 minutes 32 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 :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

Java Enums

Or Copy Link

CONTENTS
Scroll to Top