In Java enumerations (enums), represent a group of name constants, providing a robust way to manage sets of relative constants with type safety. While converting an enum value to a String is straight forward, transforming a String back into a corresponding enum value is a task that often arises in scenarios where you are dealing with user input or external data sources. In this article, we will explore the process of converting strings to enum values in Java.
Table of Contents
Converting String to Enum
Java provides a built-in method to facilitate the conversion of a String to its corresponding enum value. Enum.valueOf()
, This static method is part of the Enum class and can be used to convert in String, provided it matches the name of an enum constant in the specified enum type.
String to Enum Conversion
public class enumToString {
enum Day{
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY;
}
public static void main(String[] args) {
String input = "SUNDAY";
Day day = Enum.valueOf(Day.class, input);
System.out.println(day);
}
}
Output
This approach is a straightforward method for String to enum conversion but it is compulsory that the input String exactly matches the name of an enum constant, including case sensitivity.
Handling Case Sensitivity
Often the input String may not match the case of enum constants. In such cases, we can normalize the input string to match the case of enumthe definition before conversion.
import java.util.Locale;
public class enumToString {
enum Day{
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY;
}
public static void main(String[] args) {
String input = "sunday";
Day day = Enum.valueOf(Day.class, input.toUpperCase());
System.out.println(day);
}
}
Output
Exception Handling during String to Enum Conversion
Directly using Enum.valueOf()
can lead to an IllegalArgumentException
if the input string does not match any enum constant. To handle this gracefully we can encapsulate the conversion logic within a try-catch block or use a custom method for a more controlled conversion process.
try{
Day day = Enum.valueOf(Day.class, input.toUpperCase());
}
catch (IllegalArgumentException e){
System.out.println(e);
}
Converting strings to enums in Java is a common requirement that can be efficiently handled using the Enum.valueOf()
method. By following the best practices such as input validation, exception handling, and input normalization we can ensure robust and error-free conversion.
Happy Coding & Learning
1 thought on “String to Enum Conversion in Java”