Write a Java Program to Lookup enum by String value

Java provides an Enum type that allows you to define a set of named constants.

Enum constants are treated as objects and can have methods, instance variables, and constructors.

In this tutorial, we will discuss how to lookup an enum by its String value in Java.


Consider the following enum definition:

public enum Color {
    RED, GREEN, BLUE
}

To lookup an enum by its String value, we can create a static method that takes a String parameter and returns the corresponding enum constant.

Here’s an example:

public static Color fromString(String colorString) {
    for (Color color : Color.values()) {
        if (color.name().equalsIgnoreCase(colorString)) {
            return color;
        }
    }
    throw new IllegalArgumentException("No enum constant " + Color.class.getName() + "." + colorString);
}

In the above code, we iterate over all the values of the enum and check if their names match the input string (case-insensitive).

If a match is found, we return the corresponding enum constant.

If no match is found, we throw an IllegalArgumentException.

Here’s how you can use the above method:

Color color = Color.fromString("RED");
System.out.println(color); // Output: RED

Note that the above code assumes that the input string matches one of the enum constants.

If you’re not sure whether the input string is valid, you should add additional validation logic.


In conclusion, looking up an enum by its String value in Java is a simple task.

You can define a static method that iterates over all the enum constants and returns the one that matches the input string.