The Enum.valueOf() method in Java returns the enum constant of a specified enum type that matches a given name as a string. For example, Day.valueOf(Day.class, "MONDAY") returns Day.MONDAY. It is a static method provided by the Enum class, and every enum type in Java inherits it automatically.
Background: Why Enums and valueOf Exist
Enums were introduced in Java 5 (JDK 1.5) as a type-safe way to define a fixed set of constants. Before enums, developers used int constants or String constants, which were error-prone because any integer or string could be passed where a specific constant was expected. Enums solve that by creating a distinct type with a closed set of values.
The valueOf method is part of the java.lang.Enum class, which all enums extend implicitly (you cannot extend Enum yourself). It provides a bridge between external input (like a database value, a user input, or a configuration file) and the enum constant. This is essential for parsing and deserialization in many applications.
How valueOf Works: The Signature and Behavior
The method has two overloads:
public static <T extends Enum<T>> T valueOf(Class<T> enumType, String name)– the general form.- Each enum type also gets an implicit
public static EnumType valueOf(String name)generated by the compiler, which is a convenience wrapper.
For example, given:
enum Day { MONDAY, TUESDAY, WEDNESDAY }
You can call:
Day d = Day.valueOf("MONDAY"); // returns Day.MONDAY
Or the explicit form:
Day d2 = Enum.valueOf(Day.class, "TUESDAY");
Both are equivalent. The method performs a case-sensitive lookup. If the name does not match any constant exactly, it throws IllegalArgumentException. If the name is null, it throws NullPointerException.
How to Choose: valueOf vs Enum.valueOf vs ordinal()
You might wonder which form to use and when to use alternatives.
- Use
Day.valueOf("MONDAY")when you know the enum type at compile time and want the simplest call. - Use
Enum.valueOf(Day.class, "MONDAY")when you have aClassobject that might be a subclass or when you are writing generic code that works with any enum type. - Avoid
ordinal()for lookup.ordinal()returns the zero-based position of the constant, but it is fragile: if you reorder the constants, the mapping changes.valueOfis based on the name, which is more stable unless you rename constants.
For example, if you store an integer in a database, using ordinal() is tempting but risky. Instead, store the name string and use valueOf to convert back. That way, adding a new constant in the middle does not break existing data.
Common Problems and How to Handle Them
The most common issue is IllegalArgumentException when the input string does not match any constant. This often happens with user input or external data that may have different casing or extra whitespace.
For case-insensitive lookup, you can write a helper method:
public static Day fromString(String s) {
for (Day d : Day.values()) {
if (d.name().equalsIgnoreCase(s)) return d;
}
throw new IllegalArgumentException("Unknown day: " + s);
}
Another issue is that valueOf does not trim whitespace. If the input is " MONDAY", it will fail. Always trim before calling.
Also, if you have a default value in mind, you can catch the exception:
Day d;
try {
d = Day.valueOf(input);
} catch (IllegalArgumentException e) {
d = Day.MONDAY; // default
}
But catching exceptions for control flow is discouraged; a helper method with a loop is often cleaner.
Comparing valueOf to Other Lookup Methods
Java enums have a few other ways to get a constant:
values()returns an array of all constants. You can iterate and compare names, which is useful for custom logic.name()returns the exact string of the constant.valueOfis essentially the inverse ofname().- Custom fields: you can add a field like
codeand a static method to look up by that field. For example:
enum Status {
ACTIVE("A"), INACTIVE("I");
private final String code;
Status(String code) { this.code = code; }
public String getCode() { return code; }
public static Status fromCode(String c) {
for (Status s : values()) {
if (s.code.equals(c)) return s;
}
throw new IllegalArgumentException("Unknown code: " + c);
}
}
This is useful when the external representation is not the same as the constant name.
In Java 8 and later, you can also use Stream to find a constant, but for small enums a simple loop is fine.
Safety and Best Practices
There are a few important safety considerations:
- Never trust external input directly – always validate or catch the exception.
- Be aware of serialization: Java’s enum serialization is special. When you deserialize an enum, Java uses
valueOfinternally to get the constant, not the constructor. This is safe as long as the constant exists. - Do not use
valueOfwith user input without handling errors – an uncaughtIllegalArgumentExceptionwill crash your program. - Case sensitivity – the method is case-sensitive. If you need case-insensitive, write a helper as shown above.
Also note that enums are inherently thread-safe because they are immutable. The valueOf method is also thread-safe; it does not modify any state.
Alternatives to valueOf
If you are using Java 8 or later, you might consider Enum.valueOf with a Map for faster lookup when you have many constants. For example:
private static final Map<String, Day> LOOKUP = Arrays.stream(Day.values())
.collect(Collectors.toMap(Day::name, Function.identity()));
public static Day get(String name) {
return LOOKUP.get(name); // returns null if not found
}
This avoids exception handling and is O(1) instead of O(n) for the linear scan in the default implementation. However, for typical enums (few constants), the built-in valueOf is perfectly fine.
Another alternative is to use a library like Apache Commons Lang’s EnumUtils.getEnum(), which is null-safe and case-insensitive by default. But that adds a dependency.
Frequently Asked Questions
What is the difference between valueOf() and name()?
name() returns the string representation of the constant, exactly as declared. valueOf() does the reverse: it takes a string and returns the constant. They are inverses of each other, provided the string matches exactly.
Can I use valueOf with a null string?
No, it throws NullPointerException if the name is null. You should check for null before calling, or use a helper that handles null.
Does valueOf work with enums that have constructors and fields?
Yes, it works with any enum, regardless of custom fields or constructors. It only uses the constant name, not the fields.
Is valueOf case-sensitive?
Yes, it is case-sensitive. If you pass "monday" for an enum with MONDAY, it will throw an exception. For case-insensitive, write a custom method.
Why do I get IllegalArgumentException even though the string looks correct?
Common reasons include extra whitespace, invisible characters, or a different case. Use trim() and print the string to see its exact value. Also, ensure the string matches the constant name exactly, including underscores.
Can I use valueOf in a switch statement?
Yes, but you don’t need to. You can switch directly on the enum constant. If you have a string, you can first convert it with valueOf and then switch on the result. However, if the string is invalid, you’ll get an exception before the switch.
Related
- Federal Reserve Balance Sheet Explained Simply
- Google Spreadsheet Counter: How to Count Cells
- Split String in Power Automate: 3 Ways
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Excel Box Plot: Show the Median Line, Not the XIn an Excel box plot, the horizontal line inside the box is the median; an X is the…
- How to Delete a Blank Page in Microsoft WordTo delete a blank page in Microsoft Word, show formatting marks, find the paragraph mark or break that…
- Excel Custom Number Format for Decimal Hours ExplainedTo display a numeric value as decimal hours in Excel, apply a custom format such as 0.00" h"…
- Google Sheets Percentage Format: How to Use ItTo apply percentage format in Google Sheets, select the cells, then go to Format > Number > Percent…
- Generate Random Number NumPy: How to Use np.randomTo generate a random number with NumPy, use the numpy.random module—for example, np.random.rand() returns a single float between…
- Why Don’t My Hyperlinks Work in Excel?Excel hyperlinks usually fail because Excel is waiting for Ctrl+click, the link points to a location that moved,…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.