# How to convert a string to an enum value in Java

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Nov 5, 2022. Topics: Java.
Canonical URL: https://attacomsian.com/blog/java-string-to-enum

> Learn how to use the valueOf() method to convert a string to an equivalent enum constant in Java.

You can use the `valueOf()` method to convert a string to an enum value in Java. The `valueOf()` method takes a string as an argument and returns the corresponding enum object.

Let us say we have the following enum class that represents the days of the week:

```java
public enum Day {
    MONDAY,
    TUESDAY,
    WEDNESDAY,
    THURSDAY,
    FRIDAY,
    SATURDAY,
    SUNDAY;
}
```

The following example demonstrates how you can convert a string to a `Day` object using the `valueOf()` method:

```java
String str = "FRIDAY";

Day enumDay = Day.valueOf(str);
System.out.println(enumDay); // FRIDAY
```

Note that the `valueOf()` method is case-sensitive. The string value must be an exact match of an enum constant, including the case. Otherwise, an `IllegalArgumentException` exception is thrown.

The following two examples will fail due to an invalid string or case mismatch:

```java
// ❌ Fail due to case mismatch
Day mismatchStr = Day.valueOf("Monday");

// ❌ Fail due to invalid value
Day invalidStr = Day.valueOf("Weekend");

// ✅ Correct value
Day correctStr = Day.valueOf("MONDAY");
```

To handle case mismatch, you can transform the given string to uppercase, as shown below:

```java
String str = "Monday";

// Transform the string to uppercase
Day enumDay = Day.valueOf(str.toUpperCase());
System.out.println(enumDay); // MONDAY
```

Alternatively, you can also use the Streams API to convert a string to an enum value:

```java
String str = "Monday";

Optional<Day> enumDay = Arrays.stream(Day.values())
        .filter(d -> d.name().equalsIgnoreCase(str))
        .findFirst();

if (enumDay.isPresent()) {
    System.out.println("✅ Enum exists: " + enumDay.get());
} else {
    System.out.println("❌ Enum does not exist!");
}

// ✅ Enum exists: MONDAY
```
