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
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • How to Convert XLS to XLSX in Java
  • Recurrent Workflows With Cloud Native Dapr Jobs
  • Java Virtual Threads and Scaling
  • Java’s Next Act: Native Speed for a Cloud-Native World

Trending

  • Solid Testing Strategies for Salesforce Releases
  • Docker Model Runner: Streamlining AI Deployment for Developers
  • Unlocking AI Coding Assistants Part 2: Generating Code
  • My LLM Journey as a Software Engineer Exploring a New Domain
  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.

By 
Brijesh Saxena user avatar
Brijesh Saxena
DZone Core CORE ·
Aug. 02, 18 · Tutorial
Likes (34)
Comment
Save
Tweet
Share
233.0K Views

Join the DZone community and get the full member experience.

Join For Free

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. 

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.

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.

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.

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 defferent 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.

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 EnumWithoutDefinedFunctions {

      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. 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

  • How to Convert XLS to XLSX in Java
  • Recurrent Workflows With Cloud Native Dapr Jobs
  • Java Virtual Threads and Scaling
  • Java’s Next Act: Native Speed for a Cloud-Native World

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!