Enum to String Conversion in Java

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.

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()

Output

Enum to String Conversion by using toString()

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().

Output

Using name() Method

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

See Also

1 thought on “Enum to String Conversion in Java”

Leave a Comment