English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Java Examples Comprehensive Guide
In this program, you will learn how to use the enum valueOf() method to convert a string value to an enum in Java.
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); } }
When running the program, the output is:
BOLD
In the above program, we have an enum TextStyle that represents the different styles a text block can have, that is, bold, italic, underline, and strikethrough.
We also have a string named style that contains the current style we want. But not all of them are used.
Then, we use the valueOf() method of the enum TextStyle to pass the style and get the required enum value.
Since valueOf() takes a case-sensitive string value, we must use the toUpperCase() method to convert the given string to uppercase.
On the contrary, if we use:
TextStyle.valueOf(style)
This program will throw an exception No enum constant EnumString.TextStyle.Bold.