Java enum to string Tutorial

In this section, we will learn how to convert enums to string in Java.

Note: we’re assuming you’re familiar with the Java enums.

Java enum to String

In the Java enum section, we mentioned that enums are nothing but classes! This means just like any other class, we can override the `toString()` method in order to set a specific string value to be returned when an enum value is involved in an operation where string values are needed.

Note: please check the Object toString() method if you’re not familiar with this method.

Converting enum to String in Java example:

class Main{
    enum Color{
    RED, GREEN, BLUE;
    @Override
    public String toString(){
        return "The color of the enum is: "+this.name();
    }
}

    public static void main(String[] args) {
        Color val1 = Color.RED; 
        Color val2 = Color.GREEN;
        System.out.println(val2.toString());
        System.out.println(val1.toString());
    }   
}

Output:

The color of the enum is: GREEN

The color of the enum is: RED
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies