Enums

An Enum (short for “enumeration”) in Java is a special class that represents a group of constants. It’s essentially a type-safe way of dealing with a fixed set of related values. Instead of using simple constants like int or String to represent fixed values, an Enum allows you to give these constants meaningful names, making your code cleaner and more understandable.

Think of Enums as an improved version of constants. While constants can be simple values like integers or strings, Enums are objects that allow more flexibility and functionality.

Why Use Enums?

  • Type Safety: Enums ensure that you can only assign predefined values, preventing invalid data from being used in your code.
  • Code Readability: Using Enums makes your code more readable by giving descriptive names to constants, making it clear what each value represents.
  • Grouping Related Constants: Enums help organize constants that belong together, like the days of the week, seasons, or status codes.

How to Define an Enum

In Java, defining an Enum is simple. Here’s a basic example:

In this example, the Enum Day defines seven constants, representing the days of the week.

Using Enums

Once you’ve defined an Enum, you can use it like this:

Here, we are assigning MONDAY to the today variable and checking if it equals MONDAY. This is much safer than using a string like "Monday" or an integer like 1.

Adding Fields and Methods to Enums

Enums can do more than just hold constants. You can add fields and methods to make them more useful. Here’s an example:

In this example, each day of the week is associated with a string value (either “Workday” or “Weekend”). The getType() method allows you to retrieve this value when needed.

Table of Enum Methods

Method Description Example
values() Returns an array of all the constants defined in the enum, in the order they are declared. Day[] days = Day.values();
valueOf(String name) Returns the Enum constant that matches the provided string (case-sensitive). Day day = Day.valueOf("MONDAY");
ordinal() Returns the index (position) of the enum constant in the list (starting from 0). int position = Day.MONDAY.ordinal();
toString() Returns the name of the enum constant (same as name() but can be overridden for custom formatting). String name = Day.MONDAY.toString();
compareTo(E o) Compares the enum constant with another, returning a negative integer, zero, or a positive integer. int result = Day.MONDAY.compareTo(Day.TUESDAY);
getDeclaringClass() Returns the Class object for the enum (the enum type). Class<?> clazz = Day.MONDAY.getDeclaringClass();
name() Returns the name of the enum constant, exactly as it was declared. String name = Day.MONDAY.name();
clone() Creates and returns a copy of the enum constant (not typically used with enums). Day dayClone = (Day) Day.MONDAY.clone(); (throws CloneNotSupportedException)