Contents

Enum explained with code examples in Java

Written by: David Vlijmincx

Introduction

Enums allow you to define a set of named constants. They give you better code readability, provide type safety, and improve code organization. In this post, we'll explore the capabilities of enums in Java and see some best practices.

Defining an Enum

To define an enum in Java, you use the enum keyword followed by the name of the enum and a list of comma-separated constants. Here's a simple example:

1
2
3
4
5
6
7
8
9
public enum DaysOfWeek {
    MONDAY,
    TUESDAY,
    WEDNESDAY,
    THURSDAY,
    FRIDAY,
    SATURDAY,
    SUNDAY
}

Each constant in the enum is an instance of the enum class itself. You can access them like this:

1
DaysOfWeek today = DaysOfWeek.MONDAY;

Enum Methods and Constructors

In Java, you can add behaviour to each enum constant. This allows you to associate additional data or behavior with each constant. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public enum HttpStatus {
    OK(200, "Success"),
    CREATED(201, "Created"),
    BAD_REQUEST(400, "Bad Request"),
    UNAUTHORIZED(401, "Unauthorized"),
    FORBIDDEN(403, "Forbidden"),
    NOT_FOUND(404, "Not Found"),
    INTERNAL_SERVER_ERROR(500, "Internal Server Error");

    private final int code;
    private final String description;

    HttpStatus(int code, String description) {
        this.code = code;
        this.description = description;
    }

    public int getCode() {
        return code;
    }

    public String getDescription() {
        return description;
    }
}

In this example, each enum constant represents an HTTP status code and is initialized with a specific code and description. The enum also provides getter methods to access these values.

Iterating Over All Enum Constants

Java provides a convenient way to iterate over all the constants of an enum using the values() method. Here's an example:

1
2
3
for (DaysOfWeek day : DaysOfWeek.values()) {
    System.out.println(day);
}

This code will output all the constants of the DaysOfWeek enum.

Getting the Total Number of Enum Constants

To get the total number of constants in an enum, you can use the values() method in combination with the length property of the returned array. Here's an example:

1
2
int totalDays = DaysOfWeek.values().length;
System.out.println("Total days in a week: " + totalDays);

This code will output the total number of constants in the DaysOfWeek enum.

Enums and Comparable Interface

In Java, all enums implicitly implement the Comparable interface. This means that enum constants can be compared using the compareTo() method. The comparison is based on the order in which the constants are declared in the enum. As you can see in the following example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
DaysOfWeek day1 = DaysOfWeek.MONDAY;
DaysOfWeek day2 = DaysOfWeek.WEDNESDAY;

int result = day1.compareTo(day2);
if (result < 0) {
    System.out.println(day1 + " comes before " + day2);
} else if (result > 0) {
    System.out.println(day1 + " comes after " + day2);
} else {
    System.out.println(day1 + " is the same as " + day2);
}

This code will output “MONDAY comes before WEDNESDAY” since MONDAY is declared before WEDNESDAY in the enum.

Enum with Parameters and Implementing Interfaces

Enums can have parameters and implement interfaces. This allows you to associate additional data with each enum constant and provide custom behavior. This is an example of that:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
public enum Size implements Measurable {
    SMALL(10),
    MEDIUM(20),
    LARGE(30);

    private final int size;

    Size(int size) {
        this.size = size;
    }

    @Override
    public int getSize() {
        return size;
    }
}

public interface Measurable {
    int getSize();
}

In this example, the Size enum has a parameter size and implements the Measurable interface. Each enum constant is initialized with a specific size value, and the getSize() method from the interface is implemented to return the size.

Using Switch Statement with Enums

Enums in Java work well with switch statements. You can use enum constants as case labels in a switch statement. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
DaysOfWeek day = DaysOfWeek.MONDAY;

switch (day) {
    case MONDAY:
        System.out.println("It's the start of the week!");
        break;
    case FRIDAY:
        System.out.println("It's the end of the work week!");
        break;
    case SATURDAY:
    case SUNDAY:
        System.out.println("It's the weekend!");
        break;
    default:
        System.out.println("It's a regular work day.");
}

This code will output “It's the start of the week!” since the day variable is set to DaysOfWeek.MONDAY.

Switch Expressions (Java 14+)

Java 14 introduced switch expressions, which provide a more concise and expressive way to handle switch cases. This looks like the following:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
public enum Color {
    RED,
    GREEN,
    BLUE
}

public String getColorName(Color color) {
    return switch (color) {
        case RED -> "Red";
        case GREEN -> "Green";
        case BLUE -> "Blue";
    };
}

In this example, the getColorName() method uses a switch expression to return the color name based on the enum constant. The arrow (->) is used to specify the value to be returned for each case.

Enum as Singleton

One cool way of using enums in Java is to use them to implement the singleton pattern. The singleton pattern ensures that only one instance of a class is created throughout the lifetime of an application. Enums, by their very nature, guarantee this behavior. In the following example a singleton INSTANCE is made using an enum:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
public enum DatabaseConnection {
    INSTANCE;

    private Connection connection;

    private DatabaseConnection() {
        // Initialize the connection
        connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "username", "password");
    }

    public Connection getConnection() {
        return connection;
    }
}

In this example, the DatabaseConnection enum has a single constant INSTANCE. The enum's constructor is private, ensuring that no other instances can be created. The getConnection() method provides access to the singleton database connection. To use the singleton, you simply call:

1
Connection conn = DatabaseConnection.INSTANCE.getConnection();

Using an enum as a singleton offers several advantages:

  • It is thread-safe and guarantees a single instance.
  • It provides a simple and expressive way to implement the singleton pattern.
  • It handles serialization and deserialization correctly.

Best Practices

When working with enums in Java, consider the following best practices:

  1. Use meaningful names for your enum constants to improve code readability.
  2. Prefer using enums over integer or string constants for better type safety and maintainability.
  3. Leverage enum methods and constructors to encapsulate behavior and data related to the enum constants.
  4. Use the valueOf() method to safely convert strings to enum constants.
  5. Avoid using enum ordinal values for comparison or logic; rely on the enum constants themselves.

Conclusion

Enums in Java provide a powerful way to define a set of named constants, encapsulate related behavior, and ensure type safety. They offer more than just simple constants, allowing you to define methods, constructors, and implement interfaces.