This post originated from an RSS feed registered with Java Buzz
by Javin Paul.
Original Post: 2 Ways to Print Custom String Value of Java Enum
Feed Title: Java67
Feed URL: http://www.java67.com/feeds/posts/default?alt=rss
Feed Description: Java and technology tutorials, tips, questions for all programmers.
We all know that how powerful enumeration type in Java is, and one of the main strength of enum is that they can implement interface, they can have a instance variable and you can also override any method inside enum instance. In Java programs, we often need need to convert Enum to String type, sometime just to print values in log file and other time for storing log into database. By default, when you print an enum constant, it print its literal value e.g. if name of enum instance is RED, then it will print RED. This is also the value which is returned by name() method of java.lang.Enum class. But, there are situations when we want a custom String value for 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 toString() method for each enum constant and second by using an instance variable to hold custom String value. You can provide custom value while creating Enum constants and later you can call that method which returns custom String value. In this article, we will see example of these two ways.