In this post we'll see the options we have to convert an Enum to String in Java. It may be needed when you want to compare Enum to String in Java.
Converting Enum to String in Java
Enum class in Java has two methods that can convert Enum to String.
- name()- Returns the name of this enum constant, exactly as declared in its enum declaration.
- toString()- Returns the name of this enum constant, as contained in the declaration.
As per Java docs toString() should be preferred. That’s what the description of the name() method says “Most programmers should use the toString() method in preference to this one, as the toString method may return a more user-friendly name”. This is because of the fact that toString() can be overridden if need be to return a more "programmer-friendly" string form.
Converting Enum to String using name() method
Following example shows how to convert Enum to String in Java using name()
method. In the example Enum constants are iterated
using the values()
method, in each iteration Enum type is converted to String using the name() method.
public class EnumToString { private enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY } public static void main(String[] args) { EnumToString ed = new EnumToString(); ed.displayDays(); } private void displayDays(){ Day[] allDays = Day.values(); for(Day d : allDays){ String day = d.name(); System.out.println("Day of week- " + day); } } }
Output
Day of week- SUNDAY Day of week- MONDAY Day of week- TUESDAY Day of week- WEDNESDAY Day of week- THURSDAY Day of week- FRIDAY Day of week- SATURDAY
Converting Enum to String using toString() method
Following example shows how to convert Enum to String using toString()
method. In the example toString() is overridden with
in the Enum type to return a short form of the day. Note that it is not always required to override toString() method,
here it is done just to demonstrate how it can be used to return a more "programmer-friendly" string form.
public class EnumToString { private enum Day { SUNDAY("Sun"), MONDAY("Mon"), TUESDAY("Tue"), WEDNESDAY("Wed"), THURSDAY("Thu"), FRIDAY("Fri"), SATURDAY("Sat"); private String shortDay; Day(String shortDay){ this.shortDay = shortDay; } @Override public String toString() { return shortDay; } } public static void main(String[] args) { EnumToString ed = new EnumToString(); ed.displayDays(); } private void displayDays(){ Day[] allDays = Day.values(); for(Day d : allDays){ String day = d.toString(); System.out.println("Day of week- " + day); } } }
Output
Day of week- Sun Day of week- Mon Day of week- Tue Day of week- Wed Day of week- Thu Day of week- Fri Day of week- Sat
That's all for this topic Converting Enum to String in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!
>>>Return to Java Programs Page
Related Topics
You may also like-