How to convert Enum to String in Java?



There are two ways to convert an Enum to String in Java, first by using the name() method of Enum which is an implicit method and available to all Enum, and second by using toString() method. name() method of Enum returns the exact same String which is used to declare a particular Enum instance like in WeekDays Enum if we have MONDAY as one Enum instance then the name() will return String "MONDAY". This method of conversion from Enum to String is useful if the String representation of Enum is the same as its String name but if you have different String representation then you can use toString() method.


Both ways of converting Enum to String have their own merit and use cases. Prefer name() method if Stringrepresentation of Enum instance is its declared name and prefer toString() method if every Enum Instance has its own custom String representation.


You can just iterate or print values or do anything you would like to with those constants. In this example, you can see we have two enums Weekdays and ColdDrink, first uses the name() method for converting the Enum constant to String while the second uses the toString() method instead.


Code:
package example;
 
/**
 * Java program to demonstrate how to convert Enum to String in Java. This program demonstrates
 * two examples by using the name() and toString() method to get a meaningful String representation
 * from an Enum instance in Java.
 *
 * @author Javin Paul
 */
public class EnumToString {
    private enum Weekdays