1. Introduction

In this short tutorial, we’ll learn how to quickly convert a String into an enum in Java.

2. Setup

We’re dealing with core Java, so we don’t need to add any additional artifacts. We’ll also be working with the PizzaDeliveryStatusEnum from the enums guide article.

3. The Conversion

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

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 we should avoid it 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 will 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 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 brief article, we illustrated how to convert a String into an enum.

We highly recommend using 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.