Course contentsShow
← Java
Lesson 583 of 2,87014. EnumerationsFree lesson

The valueOf(String) Method

Converting a string to an enum constant using valueOf, and handling IllegalArgumentException for invalid names.

The valueOf(String) Method

What you'll learn: How to convert a text string into the corresponding enum constant and handle cases where the string doesn't match any enum value.

Converting Strings to Enum Constants

Sometimes you need to turn a string (maybe from user input or a file) into an enum constant. The valueOf(String) method does exactly this—it takes a string name and returns the matching enum constant.

Think of it like a directory lookup: You provide a name, and Java searches through your enum's constants to find an exact match. If found, you get that constant back; if not found, Java throws an exception.

Basic Syntax

enum Day {
    MONDAY, TUESDAY, WEDNESDAY
}

Day day = Day.valueOf("TUESDAY");  // Returns Day.TUESDAY

The string must match the constant name exactly—same spelling, same capitalization. "tuesday" or "Tuesday" won't work.

Handling Invalid Input

When the string doesn't match any constant, Java throws an IllegalArgumentException:

enum Status {
    ACTIVE, INACTIVE, PENDING
}

// This works fine
Status s1 = Status.valueOf("ACTIVE");

// This throws IllegalArgumentException
Status s2 = Status.valueOf("DELETED");  // No such constant!

Safe Usage Pattern

You can protect your code with a try-catch block:

try {
    Status status = Status.valueOf(userInput);
    System.out.println("Valid status: " + status);
} catch (IllegalArgumentException e) {
    System.out.println("Invalid status entered!");
}

This prevents your program from crashing when users provide unexpected input.

When to Use It

valueOf is essential when converting external data (config files, user input, API responses) into type-safe enum constants. It bridges the gap between the string world and the enum world.

Key Takeaway: The valueOf(String) method converts a string to its matching enum constant using exact name matching, throwing IllegalArgumentException if no match exists—always handle this exception when processing external input.