Java Program to Lookup enum by String value

To understand this example, you should have the knowledge of the following Java programming topics:


Example: Lookup enum by string value

public class EnumString {

    public enum TextStyle {
        BOLD, ITALICS, UNDERLINE, STRIKETHROUGH
    }

    public static void main(String[] args) {

        String style = "Bold";

        TextStyle textStyle = TextStyle.valueOf(style.toUpperCase());

        System.out.println(textStyle);
    }
}

Output

BOLD

In the above program, we have an enum TextStyle which represents the different styles a block of text can have, i.e. Bold, Italics, Underline, Strikethrough.

We also have a string named style which holds the current style we want. However, it is not in all-caps.

We then use the enum TextStyle's valueOf() method to pass the style and get the enum value we require.

Since valueOf() takes a case-sensitive string value, we had to use the toUpperCase() method to convert the given string to upper case.

If, instead, we'd used:

TextStyle.valueOf(style)

the program would've thrown an exception No enum constant EnumString.TextStyle.Bold.

Did you find this article helpful?

Your builder path starts here. Builders don't just know how to code, they create solutions that matter.

Escape tutorial hell and ship real projects.

Try Programiz PRO
  • Real-World Projects
  • On-Demand Learning
  • AI Mentor
  • Builder Community