Question
I have the following Java enum:
public enum Blah {
A, B, C, D
}
I want to convert a string such as "A" into the corresponding enum value, which would be Blah.A.
How can I do this in Java?
Should I use Enum.valueOf() for this? If so, what is the correct way to use it?
Short Answer
By the end of this page, you will understand how to convert a String into an enum value in Java, when to use valueOf(), what errors it can throw, and how to safely handle invalid input in real programs.
Concept
In Java, an enum is a special type that represents a fixed set of constants. In your example, Blah can only be one of these values:
ABCD
When you already have a string like "A" and want the matching enum constant Blah.A, Java provides a built-in method for that: valueOf().
For a specific enum type, the usual form is:
Blah value = Blah.valueOf("A");
This works because Java enums automatically get a static valueOf(String name) method.
Why this matters
Converting strings to enums is common in real programs because many values start as text:
- user input from forms
- query parameters in URLs
- configuration files
- JSON or CSV data
- command-line arguments
- database values
Enums help make code safer and clearer than using raw strings everywhere. Instead of checking for many string values manually, you can convert once and then work with a known set of valid constants.
Mental Model
Think of an enum like a row of labeled lockers:
- Locker
A - Locker
B - Locker
C - Locker
D
A string is like a note with a locker label written on it.
If the note says exactly A, Java can open the locker labeled A and give you Blah.A.
If the note says a, A, or Z, Java cannot find an exact match and reports an error.
So valueOf() is basically: "Find me the enum constant whose name exactly matches this text."
Syntax and Examples
The basic syntax is:
EnumType variable = EnumType.valueOf("CONSTANT_NAME");
With your enum:
public enum Blah {
A, B, C, D
}
You can do this:
Blah result = Blah.valueOf("A");
System.out.println(result); // A
Full example
public class Main {
public enum Blah {
A, B, C, D
}
public static void main(String[] args) {
String input = "A";
Blah value = Blah.valueOf(input);
System.out.println(value); // A
System.out.println(value == Blah.A);
}
}
Step by Step Execution
Consider this code:
public enum Blah {
A, B, C, D
}
public class Main {
public static void main(String[] args) {
String input = "B";
Blah value = Blah.valueOf(input);
System.out.println(value);
}
}
Step by step
- Java defines the enum
Blahwith four constants:A,B,C, andD. - In
main, the variableinputstores the string"B". Blah.valueOf(input)is called.- Java looks through the enum constants of
Blahfor one whose name is exactly"B".
Real World Use Cases
String-to-enum conversion appears often in everyday Java code.
API request parameters
A web API might receive:
status=ACTIVE
You can convert that string into an enum:
Status status = Status.valueOf(requestParam);
Configuration values
A config file might store:
environment=PRODUCTION
Then Java code can convert it to:
Environment env = Environment.valueOf(configValue);
Command-line tools
A CLI may accept modes like:
--mode=FAST
You convert that input to an enum instead of comparing strings manually.
CSV or database imports
When reading text data, enums provide a controlled set of valid values. This reduces bugs caused by typos or inconsistent strings.
Business rules
Instead of this:
(role.equals()) {
}
Real Codebase Usage
In real projects, developers rarely call valueOf() on raw input without checks. Common patterns include validation, normalization, and helper methods.
1. Normalize before converting
Blah value = Blah.valueOf(input.trim().toUpperCase());
Useful when input comes from users or external systems.
2. Guard clause for null values
valueOf() throws a NullPointerException if the input is null.
if (input == null) {
throw new IllegalArgumentException("Input cannot be null");
}
Blah value = Blah.valueOf(input);
3. Safe parsing helper
Many codebases create a utility method instead of repeating try-catch everywhere.
public static Blah parseBlah(String input) {
(input == ) {
;
}
{
Blah.valueOf(input.trim().toUpperCase());
} (IllegalArgumentException e) {
;
}
}
Common Mistakes
Here are common mistakes beginners make when converting strings to enums.
1. Using the wrong case
Broken code:
Blah value = Blah.valueOf("a");
Problem:
- enum names are
A,B,C,D "a"does not match"A"
Fix:
Blah value = Blah.valueOf("a".toUpperCase());
2. Forgetting to trim spaces
Broken code:
Blah value = Blah.valueOf(" A ");
Problem:
- the string includes spaces
- no enum constant is named
" A "
Fix:
Comparisons
| Approach | Example | Best for | Notes |
|---|---|---|---|
Blah.valueOf("A") | Blah value = Blah.valueOf("A"); | Simple exact enum lookup | Most common and shortest form |
Enum.valueOf(Blah.class, "A") | Blah value = Enum.valueOf(Blah.class, "A"); | Generic code | Useful when the enum type is passed around dynamically |
| Custom parsing method | Blah.fromText("a") | User input or external data | Lets you trim, ignore case, or map custom labels |
Manual if or switch | if (text.equals("A")) ... |
Cheat Sheet
// Exact match
Blah value = Blah.valueOf("A");
// Generic form
Blah value2 = Enum.valueOf(Blah.class, "A");
// Safer input handling
Blah value3 = Blah.valueOf(input.trim().toUpperCase());
Rules
valueOf()matches the enum constant name exactly.- It is case-sensitive.
- It does not ignore whitespace.
- It does not use custom fields or labels.
Exceptions
IllegalArgumentExceptionif no matching enum constant existsNullPointerExceptionif the input string isnull
Safe parsing pattern
public static Blah parseBlah(String input) {
if (input == null) {
return null;
}
try {
Blah.valueOf(input.trim().toUpperCase());
} (IllegalArgumentException e) {
;
}
}
FAQ
Is Enum.valueOf() the right method in Java?
Yes. If you want to convert a string to a matching enum constant by name, valueOf() is the standard built-in method.
What is the difference between Blah.valueOf() and Enum.valueOf()?
Blah.valueOf("A") is shorter and more common. Enum.valueOf(Blah.class, "A") is the generic version.
Does valueOf() ignore uppercase and lowercase?
No. It is case-sensitive. "A" works, but "a" does not unless you convert the string first.
What happens if the string does not match any enum constant?
Java throws an IllegalArgumentException.
What happens if I pass null to valueOf()?
Java throws a NullPointerException.
Can I convert a custom enum field like "active" using valueOf()?
Mini Project
Description
Build a small Java program that reads a text value and converts it into an enum safely. This demonstrates how to use valueOf(), how to normalize input, and how to handle invalid values without crashing the program.
Goal
Create a program that converts user-provided text into a Blah enum value and prints either the matched enum or a helpful error message.
Requirements
- Define an enum named
Blahwith the valuesA,B,C, andD. - Write a method that accepts a
Stringand tries to convert it to aBlahvalue. - Make the conversion ignore leading and trailing spaces.
- Make the conversion accept lowercase input such as
"a". - Return a safe result for invalid input instead of crashing.
Keep learning
Related questions
Avoiding Java Code in JSP with JSP 2: EL and JSTL Explained
Learn how to avoid Java scriptlets in JSP 2 using Expression Language and JSTL, with examples, best practices, and common mistakes.
Choosing a @NotNull Annotation in Java: Validation vs Static Analysis
Learn how Java @NotNull annotations differ, when to use each one, and how to choose between validation, IDE hints, and static analysis tools.
Convert a Java Stack Trace to a String
Learn how to convert a Java exception stack trace to a string using StringWriter and PrintWriter, with examples and common mistakes.