Conversion of String to Enum in Java

Hey Everyone! In this article, we will learn how to convert a string to an enum data type in Java.

Enum in Java

Enum is a special data type in Java in which it’s field consists of a fixed set of constants.
Enum is declared using the keyword ‘enum’ in java.
It was introduced in java 1.5.

public enum Directions {

It can be accessed as follows:-

Directions dr = Directions.NORTH;

Note that the constants included in the enum field are always written in CAPITAL (a certain writing convention is followed).

String to Enum

Now consider a case in which the string that is accepted in the code is to be converted to enum data type in java.
For that, the value of the method is used that is defined for enum data types.
The declaration of the method is as follows:-
public static T valueOf(String str)

This method accepts a string passed as a parameter and then converts it to the corresponding enum data type constant.
The IllegalArgumentException exception is thrown if no corresponding enum data type is found.

Thus the string that is passed as a parameter to the value of static method should match to the corresponding enum data type defined in its fields

Now Let’s have a look at the code:-

Java program to convert String to Enum in Java

package stringtoenum;

import java.util.Scanner;

enum Directions{
public class StringToEnum {

    public static void main(String[] args) {
        StringToEnum ste = new StringToEnum();
        Scanner sc = new Scanner(;
       String str;
        System.out.println("Enter string ");
        str = sc.nextLine();
    public static void convert(String str)
        Directions dr = Directions.valueOf(str.toUpperCase());
        System.out.println("The corresponding enum constant is " +dr);


Enter string 
The corresponding enum constant is WEST

I hope you have understood the article.
If you have any suggestion feel free to comment down below.


Also, read:

Leave a Reply

Your email address will not be published. Required fields are marked *