How to convert Enum to String in Java with Example

Enum to String Conversion Example in Java
There are two ways to convert an Enum to String in Java, first by using name() method of Enum which is implicit method and available to all Enum and second by using toString() method. name() method of Enum returns exact same String which is used to declare a particular Enum instance like in WeekDays Enum if we have MONDAY as one Enum instance than the name() will return String "MONDAY". This method of conversion from Enum to String is useful if String representation of Enum is same as its String name but if you have different String representation then you can use toString() method. Since Enum in Java allows a programmer to override an inherited method and since Enum has access to all Object class method, you can easily override toString() method to provide a custom String implementation for an Enum instance which can further use to convert that Enum instance to String in Java.

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

For example, if declared enum is RED and you want text representation as "RED" then use name() method because both are same, but if you want String representation as "Red" then you can use toString() method to customize that bit.

Its actually better to use toString() from maintenance perspective because if any developer refactor and change the name of Enum constant then its String representation will also change, which is not a desirable coupling and should be avoided at all cost. 


Java Example to Convert Enum to String
In following example we will see both way of converting Enum into String in Java. This program also demonstrate use of Enum.values() method which returns all Enum instances, which can be use to iterate over all enum constants. You can just iterate or print values or do anything you would like to with those constants.

How to change Enum to String in Java with Example
In this example, you can see we have two enums Weekdays and ColdDrink, first uses name() method for converting Enum constant to String while second uses toString() method instead.

package example;
 
/**
 * Java program to demonstrate how to convert Enum to String in Java. This program demonstrate
 * two examples by using 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

That’s all on How to convert Enum into String in Java. Enum provides different ways to return meaningful String representation with utmost flexibility offered by allowing overriding toString method in Java. For most cases name() method would be enough to convert Enum to String.

If you want to read further about Enum, check out this amazing Java Enum Tutorials from Java67 Blog :
  1. How to use valueOf method of Enum (check here)
  2. How to loop over Enum constants in Java (example)
  3. Top 15 Java Enum Interview Questions with Answers (see here)
  4. Can we use Enum in Switch Statement in Java (Yes)
  5. Java tip to convert  Enum to String in Java (see tip)
  6. String to Enum in Java with Example (check here)
  7. Difference between RegularEnumSet and JumboEnumSet in Java (read here)
  8. What Every Java Programmer Should know about Enum (click here)
  9. 10 points about Enum in Java (see here)
  10. Learn how to use Enum in Java with a Simple Example (check here)
  11. Can Enum have Constructor in Java (learn here)

3 comments:

  1. Good article, but I always confuse between name() and toString() method for converting Enum to String. Since toString() is an standard way of converting any object into String in Java, I think to prefer that over name(), but same time, isn't it making consistent with Enum constant has some value?

    ReplyDelete
    Replies
    1. toString() by default returns the same value as name(). name() is just there so you know what it's called in Java code since you can override toString().

      Delete
  2. Helped me a lot to understand enums. Thanks.

    ReplyDelete