[java] How to get an enum value from a string value in Java?

java.lang.Enum defines several useful methods, which is available to all enumeration type in Java:

  • You can use name() method to get name of any Enum constants. String literal used to write enum constants is their name.
  • Similarly values() method can be used to get an array of all Enum constants from an Enum type.
  • And for the asked question, you can use valueOf() method to convert any String to Enum constant in Java, as shown below.
public class EnumDemo06 {
    public static void main(String args[]) {
        Gender fromString = Gender.valueOf("MALE");
        System.out.println("Gender.MALE.name() : " + fromString.name());
    }

    private enum Gender {
        MALE, FEMALE;
    }
}

Output:
Gender.MALE.name() : MALE

In this code snippet, valueOf() method returns an Enum constant Gender.MALE, calling name on that returns "MALE".