Converting Strings to Enums in Java

1. Introduction

In this short article, we will see how to convert a String into an enum in Java quickly.

2. Setup

We are dealing with core Java so we do not need to add any additional artifacts. We will work with the PizzaDeliveryStatusEnum from the enums guide article.

3. The Conversion

Enums are similar to standard Java classes, and their values can be accessed using the dot notation. So to access the READY value of PizzaDeliveryStatusEnum, we would do:

PizzaStatusEnum readyStatus = PizzaStatusEnum.READY;

This is fine, but what if we had the value of the status stored as a String, and wanted to convert it into a PizzaStatusEnum? The naive way of doing this would be to write a giant switch statement returning the correct value of the enum for each of its possible values. But writing and maintaining such code is a nightmare and should be avoided at all costs.

On the other hand, the enum type provides a valueOf() method that takes a String as an argument and returns the corresponding enum object:

PizzaStatusEnum readyStatus = PizzaStatusEnum.valueOf("READY");

We can check that this approach actually works through a unit test:

@Test
public void whenConvertedIntoEnum_thenGetsConvertedCorrectly() {
 
    String pizzaEnumValue = "READY";
    PizzaStatusEnum pizzaStatusEnum
      = PizzaStatusEnum.valueOf(pizzaEnumValue);
    assertTrue(pizzaStatusEnum == PizzaStatusEnum.READY);
}

It’s important to remember that the valueOf() method does a case-sensitive match of the argument supplied to it, so passing a value that doesn’t match the case of any of the original enum‘s values would lead to an IllegalArgumentException:

@Test(expected = IllegalArgumentException.class)
public void whenConvertedIntoEnum_thenThrowsException() {
    
    String pizzaEnumValue = "rEAdY";
    PizzaStatusEnum pizzaStatusEnum
      = PizzaStatusEnum.valueOf(pizzaEnumValue);
}

Passing a value that’s not a part of the original enum‘s values also leads to an IllegalArgumentException:

@Test(expected = IllegalArgumentException.class)
public void whenConvertedIntoEnum_thenThrowsException() {
    String pizzaEnumValue = "invalid";
    PizzaStatusEnum pizzaStatusEnum = PizzaStatusEnum.valueOf(pizzaEnumValue);
}

4. Conclusion

In this quick article, we saw how to convert a String into an enum.

It’s highly recommended that we use the built-in valueOf() method of the enum type, instead of doing the conversion ourselves.

As always, the code for this article can be found over on GitHub.

Related posts:

Introduction to Apache Commons Text
Java Program to Implement Jarvis Algorithm
Spring Cloud AWS – RDS
Java Program to Implement the Schonhage-Strassen Algorithm for Multiplication of Two Numbers
Java Program to Generate Random Numbers Using Probability Distribution Function
Java Program to Implement LinkedTransferQueue API
Java Program to Generate All Subsets of a Given Set in the Lexico Graphic Order
Java Program to Perform Naive String Matching
Java Program to Perform Complex Number Multiplication
Java Program to Find the Shortest Path from Source Vertex to All Other Vertices in Linear Time
Guide to Dynamic Tests in Junit 5
A Guide to the ResourceBundle
Java Program to Implement Sorted Circularly Singly Linked List
Autoboxing và Unboxing trong Java
Java Program to Perform Preorder Recursive Traversal of a Given Binary Tree
Recommended Package Structure of a Spring Boot Project
Pagination and Sorting using Spring Data JPA
Spring Cloud Connectors and Heroku
Guide to Apache Commons CircularFifoQueue
Java Program to Implement String Matching Using Vectors
Java Program to Implement Sieve Of Atkin
Composition, Aggregation, and Association in Java
Introduction to the Java NIO Selector
How to Replace Many if Statements in Java
Spring WebClient Filters
Generic Constructors in Java
Java Program to Perform Optimal Paranthesization Using Dynamic Programming
Copy a List to Another List in Java
Java Program to Implement Maximum Length Chain of Pairs
Java Program to Construct an Expression Tree for an Postfix Expression
Ép kiểu trong Java (Type casting)
Java – Try with Resources