Lookup Enum by String value in Java

Exercise:

Write a Java Program to lookup enum by string value.

Click Here to View the Solution!
public class EnumStringStyle {
    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);
    }
} 
Click Here to View the Output!
BOLD
Click Here to View the Explanation!
  • This program delineates the usage of valueOf() function, for transforming a String into an enum.
  • One thing to be noticed here is that enum is employed to contain un-modifiable final variables.
  • Here TextStyle enum holds around four varieties of styles namely, BOLD, italics, UnderLine and StrikeThrough.
  • Also the desired style is declared i.e. ‘Bold’ as of now; and is assigned to variable ‘style’.
  • Since it is not in the form of capital letters, therefore toUpperCase() function turns all the letters of the string to upper case.
  • All the letters are supposed to be in upper case as valueOf() method is sensitive to the case in which the characters are.
  • In other case, the code would display a message: No enum constant EnumString.TextStyle.Bold, indicating that no such style exists.
  • Finally, ‘style’ string is passed as an argument to valueOf() function, and that function is called upon TextStyle enum.
  • The results BOLD are assigned to textStyle instance, and then displayed on the console.

%d bloggers like this: