Determining if an Enum Value Exists in Java

06 May 2023 Balmiki Mandal 0 Core 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.

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.