How to Convert a String to an Enum in Java

Summary: in this tutorial, you will learn how to convert a string to an enum in Java using the valueOf() static method of the Enum class.

Converting a string to an enum constant using valueOf() method

An enum is a special class that extends the java.lang.Enum class. Typically, you use an enum to represent multiple related constants. Each constant in the enum is an instance of the enum itself.

When your Java application interacts with other subsystems such as databases or APIs, you work with strings instead of enums. In this case, you need to convert a string to an enum constant.

For simple cases, you can use the built-in static method valueOf() provided by the Enum class that converts a string to an enum constant:

public static MyEnum valueOf(String name);Code language: Java (java)

The valueOf() static method has a parameter name that must match exactly a constant declared in the MyEnum. It returns an enum constant of the MyEnum type.

If the name doesn’t match the valueOf() method throws an IllegalArgumentException.

Let’s take an example of using the valueOf() method to convert a string into an enum constant.

enum HttpStatus {
    OK(200),
    NOT_FOUND(404),
    INTERNAL_SERVER_ERROR(500);

    private final int statusCode;

    HttpStatus(int statusCode) {
        this.statusCode = statusCode;
    }

    public int getStatusCode() {
        return statusCode;
    }

    @Override
    public String toString() {
        return String.format("%d %s", statusCode, super.toString());
    }
}

public class App {
    public static void main(String[] args) {
        var response = "OK";
        var status = HttpStatus.valueOf(response);
        System.out.println(status);
    }
}Code language: Java (java)

Output:

200 OKCode language: Java (java)

How it works.

First, define an enum HttpStatus that represents HTTP statuses. The HttpStatus enum has three constants OK, NOT_FOUND, and INTERNAL_SERVER_ERROR. Each constant is associated with a status code:

  • OK – 200
  • NOT_FOUND – 404
  • INTERNAL_SERVER_ERROR – 500

Note that we use only three HTTP statuses for brevity. In practice, you’ll have many other HTTP statuses.

Second, convert the literal string "OK" to a constant of the HttpStatus enum using the static method valueOf().

Since the "OK" literal string matches exactly the OK constant of the HttpStatus enum, the program displays the OK constant on the screen.

Notice that the valueOf() method compares strings case-sensitively. If you use Ok or ok, it will not match. Hence, it’ll throw an IllegalArgumentException. For example:

var response = "Ok";
var status = HttpStatus.valueOf(response); // exception
System.out.println(status);Code language: Java (java)

In this case, you can use a try catch statement to handle the exception:

var response = "Ok";
try {
    var status = HttpStatus.valueOf(response);
    System.out.println(status);
} catch (IllegalArgumentException e) {
    System.err.println(e.getMessage());
}Code language: Java (java)

In this case, the program won’t crash but display an error message:

No enum constant HttpStatus.OkCode language: plaintext (plaintext)

What if you want to convert a status code e.g., 200 to an enum constant? In this case, you can iterate over the constants of the enum and match the status code.

For example, the following adds the static method fromStatusCode() to the enum HttpStatus that returns a constant based on a given status code. If the status code is not found, it throws an IllegalArgumentException:

enum HttpStatus {
    OK(200),
    NOT_FOUND(404),
    INTERNAL_SERVER_ERROR(500);

    private final int statusCode;

    HttpStatus(int statusCode) {
        this.statusCode = statusCode;
    }

    public int getStatusCode() {
        return statusCode;
    }

    @Override
    public String toString() {
        return String.format("%d %s", statusCode, super.toString());
    }

    public static HttpStatus fromStatusCode(int statusCode) {
        for (var status : values()) {
            if (status.getStatusCode() == statusCode) {
                return status;
            }
        }
        throw new IllegalArgumentException(String.format("No status code %d", statusCode));
    }
}

public class App {
    public static void main(String[] args) {
        var statusCode = 200;
        try {
            var status = HttpStatus.fromStatusCode(statusCode);
            System.out.println(status);
        } catch (IllegalArgumentException e) {
            System.err.println(e.getMessage());
        }
    }
}Code language: Java (java)

Output:

200 OKCode language: plaintext (plaintext)

Summary

  • Use the valueOf() static method of the Enum class to convert a string to an enum constant.