How Can I Obtain An Enum Value From A String Value In Java?

To get an enum value from a string value in Java, you can use the Enum.valueOf() method. Here’s an example:

public class Main {
    enum Day {
        MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
    }

    public static void main(String[] args) {
        String input = "FRIDAY";
        
        try {
            Day day = Enum.valueOf(Day.class, input);
            System.out.println("Enum value: " + day);
        } catch (IllegalArgumentException e) {
            System.out.println("Invalid enum value: " + input);
        }
    }
}

In this example, we have an enum called Day with different values. We want to get the enum value based on a string value input. The Enum.valueOf() method is used to achieve this. It takes two arguments: the enum class and the string value. It returns the corresponding enum value if it exists, otherwise it throws an IllegalArgumentException. Finally, we print the enum value if it is valid, or an error message if it is invalid.

About the Author Rex

I'm a passionate tech blogger with an insatiable love for programming! From my early days tinkering with code, I've delved into web dev, mobile apps, and AI. Sharing insights and tutorials with the world is my joy, connecting me to a global community of like-minded tech enthusiasts. Python holds a special place in my heart, but I embrace all challenges. Constantly learning, I attend tech conferences, contribute to open-source projects, and engage in code review sessions. My ultimate goal is to inspire the next generation of developers and contribute positively to the ever-evolving tech landscape. Let's code together!