English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java Flow Control

Java Array

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List

Java Queue (Queue)

Java Map Collection

Java Set Collection

Java Input/Output (I/O)/O)

Java Reader/Writer

Other Java Topics

Java program to find enum by string value

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.

Example: Find 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);
    }
}

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.

Java Examples Comprehensive Guide