Java: Retrieving string representation of an enum value

If you have an enum defined as such:

public enum myEnum {
   VALUE1,
   VALUE2
}

and you want to convert it to string values of VALUE1 and VALUE2 for use elsewhere, there are 2 methods available. name() and toString().

If you want to always be guaranteed that you get VALUE1 and VALUE2, you must use name(). toString() can be overridden, and depending on the enum, is likely to be.

For example, if we modified an enum to contain properties, we might want toString to reflect this.

public enum Planets {
   MERCURY("first"),
   VENUS("second"),
   EARTH("third")

   private String positionFromSun;

   public Planets(String positionFromSun) {
      this.positionFromSun = positionFromSun;
   }

   @Override
   public String toString() {
      return "The planet " + this.name() + " is the " + this.getPosition() + " planet from the sun";
   }

name() for the above enum would still return MERCURY, VENUS and EARTH whereas toString() obviously will not.

It's only fair to share...
Share on FacebookGoogle+Tweet about this on TwitterShare on LinkedIn

Leave a Reply