Java

Java Enums Explained

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.

What is an Enum in Java?

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.

Basic Enum Declaration

public enum Day {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY;
}

Here, Day is an enumeration representing the days of the week.

Features of Java Enums

  1. Type Safety: Enums prevent assigning invalid values.
  2. Singleton Nature: Enum constants are singleton instances.
  3. Can Have Fields and Methods: Enums can include variables, constructors, and methods.
  4. Implementing Interfaces: Enums can implement interfaces but cannot extend classes.
  5. Switch-Case Support: Enums work seamlessly with switch statements.

Enum Methods and Usage

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 with Fields, Constructors, and Methods

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

Enum in Switch Statements

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");
}

Implementing Interfaces in Enums

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

Enum Singleton Pattern

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

Best Practices for Using Enums

  1. Use Enums Instead of Constants: Enums provide better type safety and readability.
  2. Avoid Using Ordinal Values: Using ordinal() can lead to maintenance issues if order changes.
  3. Use Enums in Switch Statements Where Possible: Improves performance and readability.
  4. Define Custom Methods for Additional Functionality: Keeps code clean and structured.
  5. Use Enums for Singleton Pattern: Ensures thread safety and serialization handling.\

Watch a Video on Java Enums

For a more detailed explanation, watch this video on Java Enums: Java Enums Explained

Have any questions or suggestions? Share them in the comments!

About

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!

Email: developersmonks@gmail.com

Phone: +23359*******

Quick Links

  • Home
  • About
  • Contact Us
  • Categories

  • Java
  • TypeScript
  • JavaScript
  • React
  • Nextjs
  • Spring Boot
  • DevOps