π 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
Method | Description |
---|---|
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 :