2 Ways to Print Custom String Value of Java Enum

We all know that how powerful the enumeration type in Java is, and one of the main strengths of enum is that they can implement an interface, they can have an instance variable and you can also override any method inside enum instance. In Java programs, we often need to convert Enum to String type, sometimes just to print values in the log file and other times for storing log into the database.  By default, when you print an enum constant, it prints its literal value e.g. if the name of the enum instance is RED, then it will print RED. This is also the value that is returned by the name() method of java.lang.Enum class. But, there are situations when we want a custom String value for an enum constant. 

For example, I want to print Red instead of RED when I convert Enum to String. How do you do that? Well, there are two ways you can achieve this, first by overriding the toString() method for each enum constant and second by using an instance variable to hold a custom String value. 

You can provide custom values while creating Enum constants and later you can call that method which returns a custom  String value. In this article, we will see examples of these two ways.


Java Program to print custom String values to Enum in Java

As I said there are two ways you can associate a user-defined String value to an enum constant
  • By overriding toString() method
  • By Using an instance variable
In our example, we have an enumeration type called Color, it has three enum constants RED, GREEN,  and BLUE.  By default when you pass any of these enumeration constants to System.out.println() method, it will call toString() method of java.lang.Object. Since every enum by default extends java.lang.Enum, which overrides toString() method.




As shown in the following code snippet, this overridden version returns the ame, which is the literal value of the enumeration constant.

   /**
     * Returns the name of this enum constant, as contained in the
     * declaration.  This method may be overridden, though it typically
     * isn't necessary or desirable.  An enum type should override this
     * method when a more "programmer-friendly" string form exists.
     *
     * @return the name of this enum constant
     */
    public String toString() {
        return name;
    }

You can see the nice advice given in form of Javadoc comments. It clearly suggests that you should override toString() method in the enum if you need a more "programmer-friendly" string. Another way to provide a custom String is to store that value on a member value and return it by creating a custom method, remember you cannot create toString()  but can certainly create getCustomString()

Now you may think what is the difference between these two approaches? Well, there is a significant difference. The first way is actually the right way to provide custom String value because toString() is the standard method for such a task. Many frameworks and other methods like print() and println() method from System class, calls this method when you pass an enum. 

You don't get this awesome feature with any other method. Actually, the second way is the extension of associating a custom value with an enum, which could be an integer, string, or anything else. In our program, ColorWithToString overrides toString() to return custom String value and ColorWithSpecificString uses an instance variable to hold a specific String value.  

here is a full code example :


How to print custom String value of Java Enum


/**
 * Couple of ways to provide custom String values to any enum instance in Java.
 *
 * @author Javin Paul
 */
public class EnumWithCustomString{

    public static void main(String args[]) {

        System.out.println("Default String value of Java Enum Color.RED is "
                + Color.RED);
        System.out.println("Custom String value of Java Enum  ColorWithToString.RED is "
                + ColorWithToString.RED);
        System.out.println("Custom String value of Enum in Java,
 ColorWithSpecificString.RED is "
                + ColorWithSpecificString.RED.getCustomString());
    }

    /*
     * If you don't implement toString() method in Enum
     * constants, toString() will return their name e.g.
     * RED.toString() will return RED. This is also
     * same as calling RED.name() method.
     */
    private enum Color {

        RED, GREEN, BLUE;
    }

    /*
     * You can implement toString() method inside each enum
     * constant to provide a custom String value. For example
     * in below case RED.toString() will return "Red"
     */
    private enum ColorWithToString {

        RED {

                    @Override
                    public String toString() {
                        return "Red";
                    }
                },
        GREEN {

                    @Override
                    public String toString() {
                        return "Green";
                    }
                },
        BLUE {

                    @Override
                    public String toString() {
                        return "Blue";
                    }
                };
    }


    /*
     * You can also provide custom String values for Java enum, by
     * storing them in separate field. In this case toString() will
     * remain unchanged, but you can get custom String value by calling
     * your method e.g. RED.toString() will return RED, but RED.getCustomString()
     * will return "Red".
     */
    private enum ColorWithSpecificString {

        RED("red"), BLUE("blue"), GREEN("green");

        private String custom;

        private ColorWithSpecificString(String custom) {
            this.custom = custom;
        }

        public String getCustomString() {
            return custom;
        }

    }

}


Output:
Default String value of Java Enum Color.RED is RED
Custom String value of Java Enum  ColorWithToString.RED is Red
Custom String value of Enum in Java, ColorWithSpecificString.RED is red

That's all about how to print custom string values of enum in Java. As suggested by Oracle Java developers as well, the right way to return a String other than literal value is by overriding toString() method. This method is meant to provide a String value and used by many developers to convert an Enum to String as well. 


Other Java Enum Tutorials You may Like :
  1. Top 15 Java Enum Interview Questions with Answers (see here)
  2. Difference between RegularEnumSet and JumboEnumSet in Java (read here)
  3. What Every Java Programmer Should know about Enum (click here)
  4. 10 points about Enum in Java (see here)
  5. Learn how to use Enum in Java with a Simple Example (check here)
  6. Can Enum have Constructor in Java (learn here)
  7. Can we use Enum in Switch Statement in Java (Yes)
  8. How to use the valueOf method of Enum (check here)
  9. How to loop over Enum constants in Java (example)
  10. Java tip to convert  Enum to String in Java (see tip)
  11. String to Enum in Java with Example (check here)
The second method also highlights, how you can use enum as a full-blown class, defining instance variable, creating methods and writing code there. You can use this technique to associate anything with your enum constant in Java.

1 comment:

  1. I think you forget the most important message, use Enum instead of String. Anywhere you think you pass String which is fixed and well known, consider using enumeration type. Enum is better, robust and easy to use.

    ReplyDelete

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