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.
Example:-

public enum Directions {
  NORTH,
  SOUTH,
  WEST,
  EAST;
}

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{
    NORTH,
    SOUTH,
    EAST,
    WEST
}
public class StringToEnum {

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

Output:-

Enter string 
WesT
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 *