top of page

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 {
        MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
    } 

    private enum ColdDrink {
        PEPSI("Pepsi"), COKE("Coca Cola"), SPRITE("Sprite");
        private String brandname;
        private ColdDrink(String brand) {
            this.brandname = brand;
        }
       
        @Override
        public String toString(){
            return brandname;
        }
    }
   
   
    public static void main(String args[]) {
        //Converting Enum to String by using name() method
        //by default print mehtod calls toString() of enum
        ColdDrink[] drinks = ColdDrink.values();
        for (ColdDrink drink : drinks) {
            System.out.printf("String to Enum example using name :  %s%n", 
            drink.name());
        }

        //Converting Enum to String using toString() method
        for (ColdDrink drink : drinks) {
            System.out.println("String to enum conversion using toString() 
            : " + drink);
        }
    }
}

Output:
String to Enum example using name:  PEPSI
String to Enum example using name:  COKE
String to Enum example using name:  SPRITE
String to enum conversion using toString() : Pepsi
String to enum conversion using toString() : Coca Cola
String to enum conversion using toString() : Sprite


Source: Java67


The Tech Platform

0 comments
bottom of page