Java Program to Lookup enum by String value

In this program, you’ll learn to convert a string value to a enum in Java using enum’s valueOf() method.

Example: Lookup enum by string value

  1. public class EnumString {
  2. public enum TextStyle {
  3. BOLD, ITALICS, UNDERLINE, STRIKETHROUGH
  4. }
  5. public static void main(String[] args) {
  6. String style = "Bold";
  7. TextStyle textStyle = TextStyle.valueOf(style.toUpperCase());
  8. System.out.println(textStyle);
  9. }
  10. }

When you run the program, the output will be:

BOLD

In the above program, we’ve 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 case-senstitive string value, we had to use 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.