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:

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:

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:

// ❌ 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:

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:

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

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.