If you’re working with Spring, check out "REST With Spring":

>> CHECK OUT THE COURSE

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.

The new Certification Class of "REST With Spring" is finally out:

>> CHECK OUT THE COURSE