Java

Enumerated Types

Enumerated types, also known as enums, in Java are a special data type that enables a variable to be in a restricted set of named values. The enum keyword offers a way to define a group of related constants in a type-safe manner, improving code readability and robustness.

Features

Type-Safe: Enums ensure that the values are constants and can’t be changed after their definition. This guarantees that the variable can only take one of the predefined values.

Own Namespace: Each enum has its own namespace, meaning you can’t have two enum constants with the same name in the same enum.

Class Type: Though enum appears to be a list of values, under the hood, it’s a class. Each of the enum constants behaves like a public static final field.

Methods and Fields: Enums in Java can have fields, constructors, and methods, just like any other class, which can be used to add behavior to the individual constants.

Implements Interfaces: Enums can implement interfaces, allowing each constant to provide different behavior for the method declared in the interface.

Examples

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

Here, each constant has an associated type (“Weekday” or “Weekend”), and you can access this information using the getType() method.

public enum Day {
    MONDAY("Weekday"),
    TUESDAY("Weekday"),
    // ... other days ...
    SUNDAY("Weekend");

    private final String type;

    Day(String type) {
        this.type = type;
    }

    public String getType() {
        return type;
    }
}

Using enums

Day day = Day.MONDAY;

if (day == Day.SATURDAY || day == Day.SUNDAY) {
    System.out.println("It's a weekend!");
} else {
    System.out.println("It's a weekday.");
}

//Used in a switch statement

switch(day) {
    case MONDAY:
        // Action for Monday
        break;
    // Cases for other days...
    default:
        // Default action
}

Enum methods

  • values(): Returns an array of the enum’s values.
  • valueOf(String name): Returns the enum constant of the specified string value, if it exists.

Best Practices:

  • Use enums when a variable can only take one out of a small set of possible values.
  • Enums are more powerful than static final int constants because they provide type-safety.
  • Enums can be easily used in switch statements.

Enums in Java, by providing a type-safe and readable way to represent fixed sets of constants, are highly useful in scenarios where you need to represent predefined values, such as days of the week, states of a game, types of messages, etc.