How to convert a string to enum in Java

In Java, an enum is a special type representing a group of constants (unchangeable variables). Each enum constant is an instance of the enum type, and they are typically used to represent a fixed set of related values, such as states in a state machine, days of the week, or categories in a classification.

Retrieving enum values from strings

We can use the valueOf() method provided by the enum class to get an enum value from a string. The valueOf() method takes a string and returns the enum constant of the specified enum type with the specified name.

Let’s use an enum related to traffic light colors. Here’s how to convert a string to an enum value using the TrafficLight enum.

Define the enum

First, define an enum with traffic light colors.

public enum TrafficLight {
RED, YELLOW, GREEN;
}
An enum named TrafficLight that represents the traffic light colors

Convert a string to enum

Next, we will use the valueOf() method to convert a string to the corresponding enum constant. Here is a simple Java program that demonstrates this:

EnumExample.java
TrafficLight.java
public class EnumExample {
public static void main(String[] args) {
// String to be converted to enum
String lightString = "YELLOW";
// Convert the string to enum using valueOf (case-sensitive)
try {
TrafficLight light = TrafficLight.valueOf(lightString);
System.out.println("Traffic Light: " + light);
} catch (IllegalArgumentException e) {
System.out.println("Invalid traffic light color: " + lightString);
}
}
}

Code explanation

In the code above:

  • In the TrafficLight.java file:

    • Lines 1–3: It defines an enum for traffic light colors.

  • In the EnumExample.java file:

    • Line 8: It converts a string to the corresponding enum constant.

    • Lines 10–11: It handles cases where the input string does not match any enum constants by catching exceptions and printing an error message.

Handling case sensitivity

The valueOf() method is case-sensitive, so green would not match GREEN. To handle different cases, we can convert the input string to uppercase (or lowercase) before calling the valueOf() method.

Here’s an improved example:

EnumExample.java
TrafficLight.java
public class EnumExample {
public static void main(String[] args) {
// String to be converted to enum
String lightString = "green";
// Convert the string to enum using valueOf
try {
TrafficLight light = TrafficLight.valueOf(lightString.toUpperCase());
System.out.println("Traffic Light: " + light);
} catch (IllegalArgumentException e) {
System.out.println("Invalid traffic light color: " + lightString);
}
}
}

Applications

Converting a string to an enum value in Java is a common operation with various practical applications across different domains.

  • Handling user input: Users select an option from a drop-down menu in a web application. The selected option, received as a string, is converted to an enum value to handle the corresponding logic.

  • Configuration settings: Reading configuration values from a file. Configuration values are stored as strings and converted to enums to standardize the settings throughout the application.

  • Command-line arguments: A command-line tool accepts various commands or modes of operation. The command-line arguments, provided as strings, are converted to enums to control the flow of the program.

  • Database integration: The enum values are stored as strings in a database. When retrieving these values from the database, they are converted back to enums to enforce type safety and consistency in business logic.

  • Web services and APIs: The enum values are sent and received as strings in JSON payloads. JSON payloads containing enum values as strings are converted to enums for internal processing and validation.

Conclusion

Converting strings to enum values in Java is a straightforward yet powerful technique that enhances code readability, safety, and maintainability. By understanding and utilizing enums effectively, developers can handle a wide range of scenarios, from user inputs to configuration settings, with greater ease and reliability. Embracing enums in your Java applications ensures a more structured and error-resistant approach to managing constant values.

Copyright ©2024 Educative, Inc. All rights reserved