Java Enums (short for Enumerations) are a significant feature added to Java 5 that allows developers to establish a fixed set of named constant values. Unlike standard integer constants, Enums in Java offer type safety, greater readability, and more functionality. In this book, we'll go over Java Enums in detail, including their creation, usage, advanced approaches, and best practices.
In Java, an enum is a specific data type that defines collections of constants. Each value inside an Enum is referred to as an enum constant, and it is implicitly public, static, and final.
public enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY; }
Here, Day is an enumeration representing the days of the week.
Java Enums come with several built-in methods:
1. values() - Get All Enum Constants
for (Day d : Day.values()) { System.out.println(d); }
2. ordinal() - Get Index of Enum Constant
System.out.println(Day.MONDAY.ordinal()); // Output: 1
3. name() - Get the Name of the Enum Constant
System.out.println(Day.FRIDAY.name()); // Output: FRIDAY
4. valueOf() - Convert String to Enum Constant
Day day = Day.valueOf("SUNDAY"); System.out.println(day);
Enums can have additional fields and methods.
public enum Status { SUCCESS(200, "OK"), ERROR(500, "Internal Server Error"), NOT_FOUND(404, "Not Found"); private final int code; private final String message; Status(int code, String message) { this.code = code; this.message = message; } public int getCode() { return code; } public String getMessage() { return message; } }
Usage Example
Status status = Status.SUCCESS; System.out.println(status.getCode()); // Output: 200 System.out.println(status.getMessage()); // Output: OK
Enums work efficiently with switch.
Day today = Day.MONDAY; switch (today) { case MONDAY: System.out.println("Start of the workweek!"); break; case FRIDAY: System.out.println("Weekend is near!"); break; default: System.out.println("Regular day"); }
Enums can implement interfaces but cannot extend classes.
interface Printable { void print(); } public enum Priority implements Printable { HIGH, MEDIUM, LOW; @Override public void print() { System.out.println("Priority level: " + this.name()); } }
Usage
Priority p = Priority.HIGH; p.print(); // Output: Priority level: HIGH
Enums provide a robust way to implement the Singleton pattern in Java.
public enum Singleton { INSTANCE; public void doSomething() { System.out.println("Singleton using Enum"); } }
Usage
Singleton.INSTANCE.doSomething(); // Output: Singleton using Enum
For a more detailed explanation, watch this video on Java Enums: Java Enums Explained
Have any questions or suggestions? Share them in the comments!
At DevelopersMonk, we share tutorials, tips, and insights on modern programming frameworks like React, Next.js, Spring Boot, and more. Join us on our journey to simplify coding and empower developers worldwide!