Java Program to Lookup Enum by String Value

In this java program, we will about how to lookup an enum by it's string value using valueOf() methods of java enum. In Java, an enum is a special class that represents a group of constants (unchangeable variables, like final variables). We use the enum keyword to declare enums in java. For example:

enum Fruits { 
   APPLE, ORANGE, MANGO, BANANA 
}
Here, we have created an enum called Fruits. It contains fixed constants for APPLE, ORANGE, MANGO and BANANA.


Java Program to lookup enum by string value

public class EnumLookupByString {
  public enum Fruits {
    APPLE, ORANGE, MANGO, BANANA
  }

  public static void main(String args[]) {
    String fruit = "Apple";
    Fruits fruitEnum = Fruits.valueOf(fruit.toUpperCase());
    System.out.println(fruitEnum);
  }
}
Output
APPLE

In the above java program, we have an enum Fruits which represents the different fruits available right now. We use the valueOf() method of Fruits enum class to get the enum constant corresponding to the string value. If no enum constant exist for the given string then valueOf() method will throw IllegalArgumentException.

Exception in thread "main" java.lang.IllegalArgumentException: 
	No enum constant com.tcc.java.tutorial.examples.EnumLookupByString.Fruits.GRAPES


Java Program to lookup enum by string value using user defined method

In this java program, we created a used defined method called getEnumByString inside Fruits enum class to return enum constant corresponding to given string if present otherwise it will return null.

public class EnumLookupByStringMethod {
  public enum Fruits {
    APPLE, ORANGE, MANGO, BANANA;

    public static Fruits getEnumByString(String str) {
      for (Fruits fruit : Fruits.values()) {
        if (str.toUpperCase().equals(fruit.name())) {
          return fruit;
        }
      }
      System.out.println("Not a valid enum");
      return null;
    }
  }

  public static void main(String args[]) {
    String apple = "Apple";
    String grapes = "Grapes";

    Fruits appleEnum = Fruits.getEnumByString(apple);
    if (appleEnum != null) {
      System.out.println(appleEnum);
    }

    Fruits grapesEnum = Fruits.getEnumByString(grapes);
    if (grapesEnum != null) {
      System.out.println(appleEnum);
    }
  }
}
Output
APPLE
Not a valid enum