All 15 Enums questions
More in Enums
Advertisement
Java › Enums

What is the valueOf() method on an enum, and what happens when you pass a name that doesn't match any declared constant?

Intermediate

Answer

The implicitly-generated static valueOf(String name) method looks up and returns the enum constant whose declared identifier exactly matches the given String (case-sensitive), throwing IllegalArgumentException if no constant with that exact name exists -- useful for parsing an enum from external string input (like a configuration value or API parameter), though because it throws rather than returning a sentinel/null, callers must be prepared to catch IllegalArgumentException or validate the input beforehand if invalid values are a realistic possibility.
enum Status { ACTIVE, INACTIVE, PENDING }

Status s = Status.valueOf("ACTIVE");     // works, returns Status.ACTIVE

try {
    Status invalid = Status.valueOf("active");  // throws IllegalArgumentException -- case-sensitive!
} catch (IllegalArgumentException e) {
    System.out.println("Invalid status value");
}
Real-world example An API endpoint parsing a status query parameter into a Status enum via valueOf() wraps the call in a try-catch to return a clean 400 Bad Request error with a helpful message when a client submits an invalid or mistyped status value, rather than letting an unhandled IllegalArgumentException propagate as a generic 500 error.

Common follow-ups: Why is valueOf() case-sensitive, and what would you do to support case-insensitive lookup instead?;How does this built-in valueOf() differ from the custom fromCode()-style lookup pattern for external representations that don't match Java identifier naming?