How do I get enum constant value corresponds to a string?

The valueOf() method of an enum type allows you to get an enum constant that the value corresponds to the specified string. Exception will be thrown when we pass a string that not available in the enum.

package org.kodejava.basic;

public enum Day {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}
package org.kodejava.basic;

public class EnumValueOfTest {
    public static void main(String[] args) {
        // Using valueOf() method we can get an enum constant whose
        // value corresponds to the string passed as the parameter.
        Day day = Day.valueOf("SATURDAY");
        System.out.println("Day = " + day);
        day = Day.valueOf("WEDNESDAY");
        System.out.println("Day = " + day);

        try {
            // The following line will produce an exception because the
            // enum type does not contain a constant named JANUARY.
            day = Day.valueOf("JANUARY");
            System.out.println("Day = " + day);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }
    }
}

The output of the code snippet above:

Day = SATURDAY
Day = WEDNESDAY
java.lang.IllegalArgumentException: No enum constant org.kodejava.basic.Day.JANUARY
    at java.base/java.lang.Enum.valueOf(Enum.java:273)
    at org.kodejava.basic.Day.valueOf(Day.java:3)
    at org.kodejava.basic.EnumValueOfTest.main(EnumValueOfTest.java:15)
Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.