Skip to content

How to get an enum value from a string value in Java

To get an enum value from a string value in Java, you can use the valueOf method of the enum type. Here's an example of how you might do this:


java
public enum Color {
  RED, GREEN, BLUE
}

// ...

String colorString = "RED";
Color color = Color.valueOf(colorString);

This will convert the string value to the corresponding enum value.

Keep in mind that the valueOf method will throw an IllegalArgumentException if the specified string does not match any of the enum values. Both Color.valueOf() and Enum.valueOf(Color.class, name) share this identical exception behavior. To handle invalid input gracefully, you can wrap the call in a try-catch block or use a safe lookup method:


java
public static Color fromString(String name) {
    try {
        return Color.valueOf(name);
    } catch (IllegalArgumentException e) {
        return null; // or handle the missing value as needed
    }
}

I hope this helps! Let me know if you have any other questions.

Dual-run preview — compare with live Symfony routes.