BM Balmiki Mandal 06 May 2023 27 views 0 comments Core Java

Determining if an Enum Value Exists in Java

Check if an Enum Value Exists in Java

Java enumerations are a powerful tool that can simplify and clean up your code. Enumerations define a set of named constants that can be used in place of numbers or strings in your program. In this post, we will explore how to easily check if an enum value exists in Java.

Using the Enum.valueOf() Method

The simplest way to check if an enum value exists is to use the static method valueOf() from the java.lang.Enum class. This method will take the name of the constant as a string, and return an enum value if it exists. If the value doesn't exist, it will throw an exception. Here's an example:

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

public static void main(String[] args) {
  try {
    Days day = Days.valueOf("MONDAY");
  } catch (IllegalArgumentException ex) {
    System.out.println("No such day found!");
  }
}

Using the Enum.values() Method

Another way to check if an enum value exists is to use the values() method from the java.lang.Enum class. This static method returns an array of all of the enum values, so you can easily loop over them and check if it contains the enum you're looking for. Here's an example:

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

public static void main(String[] args) {
  String inputDay = "MONDAY";
  boolean found = false;
  
  Days[] days = Days.values();
  for (Days day : days) {
    if (day.name().equals(inputDay)) {
      found = true;
      break;
    }
  }
  
  if (found) {
    System.out.println("Day found!");
  } else {
    System.out.println("No such day found!");
  }
}

Conclusion

In this post, we explored how to use Java enums to easily check if an enum value exists. We saw two different ways to do this: using the valueOf() method and using the values() method. Both methods are relatively easy to use and understand, and are a great way to simplify your code.

0 Comments

No comments yet, Be the first to comment.

Post a Comment

Please sign in to post a comment.

Related Posts

Unlock the Ins and Outs of JavaScript Engines and Runtimes

What is a JavaScript Engine? A JavaScript engine is a program or interpreter which executes JavaScript code....

BM Balmiki Mandal 05 Sep 2023
Implementing HMACSHA256 Algorithm in Java with Key

Introducing HMACSHA256 in Java with Key HMACSHA256 is an authentication algorithm designed to secure data, su...

BM Balmiki Mandal 30 Aug 2023
HMACSHA256 Java Example - Creating Secure Message Authentication

HMACSHA256 Java Example HMACSHA256 is an advanced encryption algorithm that allows developers to create encry...

BM Balmiki Mandal 30 Aug 2023