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 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. 

Since Enum in Java allows a programmer to override an inherited method and since Enum has access to all Object class methods, you can easily override the 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 have their 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 its own custom String representation.

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

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



Java Example to Convert Enum to String

In the following example, we will see both ways of converting Enum into String in Java. This program also demonstrates the use of the Enum.values() method which returns all Enum instances, which can be used to iterate over all enum constants. 

How to convert Enum to String in Java with Example


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.

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

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 these amazing Java Enum Tutorials from Java67 Blog :
  1. How to use the 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)

6 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. Probably super late here, buuuuuut...

      name() is final; toString() is not. So, you use name() if you need to be totally sure you're getting the actual name of the enum. It's useful in reflection. For a less esoteric use, if you try to choose an enum constant using valueOf() on a user-supplied string, you might want to use name() to log the valid inputs.

      toString() is more generally useful; name() is useful in a relatively small number of use cases, but there'd be no way to do those things without it.

      Delete
    3. Hello Unknown, very useful comments. the final vs non-final just nailed it. In other words, if you need to customize the String representation of enum, toString() is the way to go.

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

    ReplyDelete

Feel free to comment, ask questions if you have any doubt.