DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Migrating My Java Codebase to EE10
  • Smarter GitHub Copilot Prompts for Java Microservices: From APIs to Production Tests
  • Google Cloud Pub/Sub vs. AWS SNS and SQS: One Java API for Both With MultiCloudJ
  • Integration Testing With MongoDB in Java: Finding the @Sql Equivalent With Liquibase/Flyway or Jamolingo

Trending

  • The Laws of Computer Science
  • Vibe Coding: Conversational Software Development — Part 2: In Practice
  • Agentic Test Creation: From Plain-Language Requirements to End-to-End Test Cases
  • Member Spotlight: Raghava Dittakavi

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Coding
  3. Java
  4. Java Enums: How to Make Enums More Useful

Java Enums: How to Make Enums More Useful

Having trouble using enums in Java? Check out this post to learn more about how to make enums more useful with or without a set of variables. Will cover latest Java Enum features (till java 26).

By 
Brijesh Saxena
·
Aug. 02, 18 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
234.6K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

In the following code, we do not use variables or any set of values as enum members. In Java, we often are required to work on a set of constants, like weekdays (Sunday, Monday, and so on), months (January, February, etc.), and many more. 

Java
 
enum WeekDays {
   SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY;
}
enum Months {
   JANUARY, FEBRAURY, MARCH, APRIL, MAY, JUNE, JULY, AUGUST, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER;
}
enum Directions {
   East, West, North, South, Up, Down
}

Because of this, we use Java enums for creating a set of constants. Let's learn more about how to use them.

About Java Enums

  1. Java enum constructors must use a private or default package-level modifier. Enums can contain multiple constructors.
  2. Java enums implicitly extend the  java.lang.Enum class. Therefore, Java enums can't extend any class. But, enums can implement different interfaces.
  3. Java enums implicitly implement the   java.lang.Comparable and  the  java.io.Serializable  interfaces.
  4. We can't instantiate an enum using the new operator.
  5. We can also provide various values as enum-member variables with the enum constants.
  6. We can create abstract methods within an enum. In that case, all of the Enum constants will become abstract and will be required to implement declared abstract methods.

In this article, I will mainly focus on these last two points — I am keeping the examples simple to focus only on the uses of the enums.

Enums With and Without Variables

The following code does not use variables or a set of values as enum members.

Java
 
enum WeekDays {
   SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY;
}
public class EnumWithoutValues {

  public static void main(String[] args) {
    WeekDays weekdays = WeekDays.THURSDAY;
    switch (weekdays) {
      case SUNDAY:
      	System.out.println("Sunday Funday");
      	doYourTaskForWeekEnds();
      break;
      case MONDAY:
      	System.out.println("Marketing Monday");
      	doYourTaskForWeekDays(weekdays);
      break;
      case TUESDAY:
      	System.out.println("Trendy Tuesday");
     	doYourTaskForWeekDays(weekdays);
      break;
      case WEDNESDAY:
      	System.out.println("Wellness Wednesday");
        doYourTaskForWeekDays(weekdays);
      break;
      case THURSDAY:
      	System.out.println("Thankful Thursday");
        doYourTaskForWeekDays(weekdays);
      break;
      case FRIDAY:
      	System.out.println("Foodie Friday");
      	doYourTaskForWeekDays(weekdays);
      break;
      case SATURDAY:
      	System.out.println("Social Saturday");
     	doYourTaskForWeekEnds();
      break;
    }
  }

  private static void doYourTaskForWeekEnds() {
    System.out.println("Relax and Enjoy! It's Weekend :)");
  }

  private static void doYourTaskForWeekDays(WeekDays weekdays) {
  System.out.println("Ohh! It's a weekday. Have to work!");
  }
}

Now, the code below uses variables or a set of values as enum members.

Java
 
enum WeekDays {
   SUNDAY("Sunday Funday", true), 
   MONDAY("Marketing Monday"),
   TUESDAY("Trendy Tuesday"), 
   WEDNESDAY("Wellness Wednesday"),
   THURSDAY("Thankful Thursday"),
   FRIDAY("Foodie Friday"),
   SATURDAY("Social Saturday", true);

  private String daysGreeting;
  private boolean isWeekend;

  WeekDays(final String daysGreeting) {
  this.daysGreeting = daysGreeting;
  }

  WeekDays(final String daysGreeting, final boolean isWeekend) {
    this(daysGreeting);
    this.isWeekend = isWeekend;
  }
  public String getDaysGreeting() {
  return daysGreeting;
  }
  public boolean isWeekend() {
  return isWeekend;
  }
}

public class EnumWithValues {

  public static void main(String[] args) {
    WeekDays weekdays = WeekDays.THURSDAY;
    System.out.println(weekdays.getDaysGreeting());
    if (weekdays.isWeekend()) {
      doYourTaskForWeekEnds();
    } else {
      doYourTaskForWeekDays(weekdays);
    }
  }

  private static void doYourTaskForWeekEnds() {
      System.out.println("Relax and Enjoy! It's Weekend :)");
  }

  private static void doYourTaskForWeekDays(WeekDays weekdays) {
      System.out.println("Ohh! It's a weekday. Have to work!");
  }
}

Enums With and Without Defined Methods

The following code uses enums without any defined methods. In this code, we are trying to perform some basic arithmetic calculations.

Java
 
enum Operator {
	ADD,
	SUBTRACT,
	MULTIPLY,
	DIVIDE;
}
public class EnumWithoutDefinedFunctions {

  public static void main(String[] args) {
    int num1 = 10;
    int num2 = 2;
    Operator operator = Operator.DIVIDE;
    int result = 0;
    switch (operator) {
      case ADD:
      result = num1 + num2;
      break;
      case SUBTRACT:
     result = num1 - num2;
      break;
      case MULTIPLY:
      result = num1 * num2;
      break;
      case DIVIDE:
            if (num2 != 0) {
                    result = num1 / num2;
            } else {
                    System.out.println("Can't divide by zero.");
            }
      break;
    }
    System.out.println("result: " + result);
  }

}

Below code uses enums with defined methods: We should define methods as abstract methods and then we have to implement different flavours/logic based on each enum members. Because of declaring abstract method at the enum level; all of the enum members require to implement the method. Basically, enum members are instances of the enum and to make it instantiable, we need to implement all of abstract methods as announemous class at each of the enum member.

Java
 
enum Operator {
    ADD {
       @Override int execute(final int num1, final int num2) {
        return num1 + num2;
        }
    },
    SUBTRACT {
      @Override int execute(final int num1, final int num2) {
    return num1 - num2;
    }
    },
    MULTIPLY {
      @Override int execute(final int num1, final int num2) {
    return num1 * num2;
    }
    },
    DIVIDE {
   @Override int execute(final int num1, final int num2) {
          if (num2 != 0) {
              return num1 / num2;
          } else {
              System.out.println("Can't divide by zero.");
          }
          return 0;
    }
};

abstract int execute(int num1, int num2);

}

public class EnumWithDefinedFunctions {

      public static void main(String[] args) {
        int num1 = 10;
        int num2 = 2;
        Operator operator = Operator.DIVIDE;
        int result = operator.execute(num1, num2);
        System.out.println("result: " + result);
      }

}

We can also combine both of the cases here — enums with variables and a set of values with defined methods.

Enums With Enhanced Switch Expressions (Java 14+)

Java 14 introduced switch expressions with arrow syntax — no break needed, and it can return a value directly.

Java
 
enum Operator {
   ADD, SUBTRACT, MULTIPLY, DIVIDE;
}

public class EnumWithSwitchExpression {

   public static void main(String[] args) {
      int num1 = 10;
      int num2 = 2;
      Operator operator = Operator.DIVIDE;

      int result = switch (operator) {
         case ADD      -> num1 + num2;
         case SUBTRACT -> num1 - num2;
         case MULTIPLY -> num1 * num2;
         case DIVIDE   -> {
            if (num2 != 0) {
               yield num1 / num2;
            } else {
               System.out.println("Can't divide by zero.");
               yield 0;
            }
         }
      };

      System.out.println("result: " + result);
   }
}

Please notice here the syntax. No break statement at needed. For single statement no return statement; just an arrow operator and the value to return. For multiple statement under a case statement; an arrow followed by code block ({}) and yield statement as return since return will make the flow out of the method. The value returned could be assigned to a variable just like we did here by assigning to 'result'.

Key benefits:

  • Exhaustiveness check — the compiler ensures all enum constants are handled.
  • No fall-through bugs — arrow syntax doesn't fall through.
  • yield keyword is used to return a value from a block within a switch expression.

Pattern Matching With Enums in Switch (Java 21+)

Java 21 finalized pattern matching in switch. When combined with sealed interfaces, enums become powerful type discriminators:

Java
 
sealed interface Shape permits Circle, Rectangle, Triangle {}
record Circle(double radius) implements Shape {}
record Rectangle(double width, double height) implements Shape {}
record Triangle(double base, double height) implements Shape {}

enum ShapeType {
   CIRCLE, RECTANGLE, TRIANGLE;

   public Shape createDefault() {
      return switch (this) {
         case CIRCLE    -> new Circle(1.0);
         case RECTANGLE -> new Rectangle(1.0, 1.0);
         case TRIANGLE  -> new Triangle(1.0, 1.0);
      };
   }
}

You can also pattern-match directly on objects when enums guide the logic:

Java
 
static String describe(Object obj) {
   return switch (obj) {
      case WeekDays d when d.isWeekend() -> "Weekend: " + d.getDaysGreeting();
      case WeekDays d                    -> "Weekday: " + d.getDaysGreeting();
      case null                          -> "No day provided";
      default                            -> "Not a day";
   };
}

Enums Implementing Interfaces With Default and Static Methods

We have seen that enums can implement interfaces. Now lets see the power of combining interfaces with Java 8+ default/static methods:

Java
 
interface Printable {
   default String format() {
      return "[" + this.toString() + "]";
   }

   static void printAll(Printable... items) {
      for (Printable item : items) {
         System.out.println(item.format());
      }
   }
}

enum Priority implements Printable {
   LOW, MEDIUM, HIGH, CRITICAL;

   @Override
   public String format() {
      return "Priority: " + name().toLowerCase();
   }
}

// Usage: Printable.printAll(Priority.values());

Enums With Records (Java 16+)

Records pair naturally with enums to create rich, immutable data associated with each constant:

Java
 
record CurrencyInfo(String symbol, int decimalPlaces) {}

enum Currency {
   USD(new CurrencyInfo("$", 2)),
   EUR(new CurrencyInfo("€", 2)),
   JPY(new CurrencyInfo("¥", 0)),
   BTC(new CurrencyInfo("₿", 8));

   private final CurrencyInfo info;

   Currency(CurrencyInfo info) {
      this.info = info;
   }

   public String symbol() { return info.symbol(); }
   public int decimalPlaces() { return info.decimalPlaces(); }
}

EnumSet and EnumMap — Optimized Collections

These have been around since Java 5 but are often overlooked. They use bitwise operations internally, making them significantly faster than HashSet/HashMap for enum keys:

Java
 
import java.util.EnumSet;
import java.util.EnumMap;

enum Permission { READ, WRITE, EXECUTE, DELETE }

public class EnumCollectionsExample {

   public static void main(String[] args) {
      // EnumSet — backed by a single long bitmask (up to 64 enum constants)
      EnumSet<Permission> adminPerms = EnumSet.allOf(Permission.class);
      EnumSet<Permission> readerPerms = EnumSet.of(Permission.READ);
      EnumSet<Permission> writerPerms = EnumSet.of(Permission.READ, Permission.WRITE);

      // Set operations
      EnumSet<Permission> diff = EnumSet.copyOf(adminPerms);
      diff.removeAll(writerPerms); // {EXECUTE, DELETE}

      // EnumMap — array-based, O(1) access
      EnumMap<WeekDays, String> schedule = new EnumMap<>(WeekDays.class);
      schedule.put(WeekDays.MONDAY, "Team standup");
      schedule.put(WeekDays.FRIDAY, "Sprint review");
   }
}

Enums as Singleton (Effective Java Pattern)

Joshua Bloch's "Effective Java" recommends single-element enums as the best way to implement singletons — they're serialization-safe and reflection-proof:

Java
 
enum DatabaseConnection {
   INSTANCE;

   private final Connection connection;

   DatabaseConnection() {
      // Initialize connection once
      connection = createConnection();
   }

   public Connection getConnection() {
      return connection;
   }

   private Connection createConnection() {
      // ... connection setup
      return null;
   }
}

// Usage: DatabaseConnection.INSTANCE.getConnection();

Enums With Functional Interfaces (Java 8+)

By release of Java 8 Functional Programming, we could combine enums with Function, BiFunction, or custom functional interfaces to avoid the verbose abstract method pattern as we have seen at the start of this article:

Java
 
import java.util.function.IntBinaryOperator;

enum Operator {
   ADD((a, b) -> a + b),
   SUBTRACT((a, b) -> a - b),
   MULTIPLY((a, b) -> a * b),
   DIVIDE((a, b) -> b != 0 ? a / b : 0);

   private final IntBinaryOperator operation;

   Operator(IntBinaryOperator operation) {
      this.operation = operation;
   }

   public int execute(int num1, int num2) {
      return operation.applyAsInt(num1, num2);
   }
}

This achieves the same result as your abstract method example but with less boilerplate.

I hope this post clarified using enums in Java in a simplistic and easy-to-understand way.

Liked the article? Don't forget to press that like button. Happy coding!

Need more articles on Design Patterns? Below are some of them I have shared with you.

  • Null Object Pattern in Java
  • Using the Adapter Design Pattern in Java

  • Using the Bridge Design Pattern in Java

  • Strategy vs. Factory Design Patterns in Java

  • Decorator Design Pattern in Java

  • How to Use Singleton Design Pattern in Java

  • Singleton Design Pattern: Making Singleton More Effective in Java

Some additional Articles:

  • Java Enums: How to Make Enums More Useful

  • Java Enums: How to Use Configurable Sorting Fields

Java (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • Migrating My Java Codebase to EE10
  • Smarter GitHub Copilot Prompts for Java Microservices: From APIs to Production Tests
  • Google Cloud Pub/Sub vs. AWS SNS and SQS: One Java API for Both With MultiCloudJ
  • Integration Testing With MongoDB in Java: Finding the @Sql Equivalent With Liquibase/Flyway or Jamolingo

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook