Big Question with Java Enum and String – Java Enum is not a Collection of Strings? – Can we convert String to Java Enum?

 

convert String to Java Enum

Can we convert String to Enum?

­­We have already discussed about Basics of Enum and important functions of Enum. Now we will see how to convert String to Java Enum and vice versa. Some people will tell that Enum is to maintain list of Strings. But I will not agree with their opinion, because Enum by itself is a TYPE it’s not a String type. To know more about this visit Things Which You Don’t Know about Java Enum.

In one of our discussion we have seen the conversion of Wrapper <-> String <-> Primitive, but is it possible to Convert Enum to String and vice versa? Yes it is. Now we will see with some example.

package com.learnfromexamples.enumtutorial.pkg4.enumconversion;

public class SubjectEnumImplementation {
    enum Subject{
        LANGUAGE,ENGLISH,MATHEMATICS,SCIENCE,SOCIALSTUDIES
    }
    public static void main(String[] args) {
        // Convert String to Enum
        Subject Language = Subject.valueOf("LANGUAGE");
        System.out.println("Language value is " +Language);
        // Check whether Language is of Type Subject
        System.out.println("Language type is " +Language.getClass());
        
        // Convert String to Enum
        Subject maths = Enum.valueOf(Subject.class, "MATHEMATICS");
        System.out.println("maths value is " +maths);
        // Check whether maths is of Type Subject
        System.out.println("maths type is " +maths.getClass());
        
        // Convert Enum to String
        String English = Subject.ENGLISH.toString();
        System.out.println("English value is " +English);
        // Check whether English is of Type String
        System.out.println("Language type is " +English.getClass());
        
    }
}

Output

Language value is LANGUAGE
Language type is class com.learnfromexamples.enumtutorial.pkg4.enumconversion.SubjectEnumImplementation$Subject
maths value is MATHEMATICS
maths type is class com.learnfromexamples.enumtutorial.pkg4.enumconversion.SubjectEnumImplementation$Subject
English value is ENGLISH
Language type is class java.lang.String

Convert String to Java Enum and Enum to String

valueOf()

To convert String to Enum we have a method called valueOf, if we see the code snippet there are two types of valueOf methods, one which belongs to our custom Enum class(i.e Subject) and another one belongs to Enum Class itself.

toString()

To convert Enum to String, it’s very simple that we can use our old toString() method.

Also to know after the conversion the output is of Correct Object type we used getClass() method, which will print the object belongs to which corresponding class. So if we see the output for Language.getClass() and maths.getClass() it prints its corresponding class com.learnfromexamples.enumtutorial.pkg4.enumconversion.SubjectEnumImplementation$Subject which says it belongs to class Subject.