Enum to String Conversion in Java. Enumeration Types ( enums) are a powerful feature introduced in Java 5, that provides options to define Collections of constants with more type safety and less maintenance overhead than traditional constant declarations. One common requirement when working with an enum is converting enum values to a String representation. In this article, we will see how we will perform enum to string conversion.
Table of Contents
Enums to String Conversion in Java
Converting an enum value to a String is straightforward in Java, thanks to the built-in toString()
method that every enum inherits from java.lang.Enum
class. This method returns the name of the enum constant exactly as declared as the enum declaration.
Enum to String Conversion by using toString()
public class enumToString {
enum Day{
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY;
}
public static void main(String[] args) {
Day day = Day.MONDAY;
String enumasstring = day.toString();
System.out.println(enumasstring);
}
}
Output
This approach is the most simple way to get a String representation of an enum value.
Alternative Approaches for Enum toString()
While the toString method is simple and effective, java also provides other ways to achieve the same result, offering flexibility for different use cases.
Using name() Method
The name() method provided by Enum class, returns the exact name of the Enum constant, similar to toString().
public class enumToString {
enum Day{
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY;
}
public static void main(String[] args) {
Day day = Day.SUNDAY;
String enumasstring = day.name();
System.out.println(enumasstring);
}
}
Output
Converting an enum value to a String in Java is a common task that can be easily accomplished by using the built-in toString() or the name() method for direct conversion.
Happy Coding & Learning
2 thoughts on “Enum to String Conversion in Java”