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.
Important rule
valueOf() matches the enum constant name exactly.
That means:
"A"works"a"does not work" A "does not work unless trimmed first
If the string does not exactly match an enum constant name, Java throws an IllegalArgumentException.
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); // true
}
}
Safer example with validation
If the input may be invalid, wrap the conversion in a try-catch block:
public class Main {
public enum Blah {
A, B, C, D
}
public static void main(String[] args) {
String input = "X";
try {
Blah value = Blah.valueOf(input);
System.out.println("Valid enum: " + value);
} catch (IllegalArgumentException e) {
System.out.println("Invalid enum value: " + input);
}
}
}
Case-insensitive conversion
If you want to accept values like "a", normalize the string first:
String input = "a";
Blah value = Blah.valueOf(input.toUpperCase());
System.out.println(value); // A
If input might contain extra spaces:
String input = " a ";
Blah value = Blah.valueOf(input.trim().toUpperCase());
System.out.println(value); // A
Generic form
There is also a generic enum API:
Blah value = Enum.valueOf(Blah.class, "A");
This does the same thing, but Blah.valueOf("A") is shorter and more common when you already know the enum type.
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". - It finds
Blah.B. - That enum value is assigned to the variable
value. System.out.println(value);printsB.
What if the input is invalid?
String input = "b";
Blah value = Blah.valueOf(input);
Now the steps change:
- Java receives the string
"b". - It looks for an enum constant named exactly
"b". - The enum only contains
A,B,C, andD. - No exact match is found.
- Java throws
IllegalArgumentException.
That is why input cleanup such as trim() and toUpperCase() is often useful when reading external data.
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:
if (role.equals("ADMIN")) {
// ...
}
You can do this:
Role role = Role.valueOf(roleText);
if (role == Role.ADMIN) {
// ...
}
This is easier to maintain and safer.
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) {
if (input == null) {
return null;
}
try {
return Blah.valueOf(input.trim().toUpperCase());
} catch (IllegalArgumentException e) {
return null;
}
}
4. Returning Optional
A cleaner approach is to avoid returning null.
import java.util.Optional;
public static Optional<Blah> parseBlah(String input) {
if (input == null) {
return Optional.empty();
}
try {
return Optional.of(Blah.valueOf(input.trim().toUpperCase()));
} catch (IllegalArgumentException e) {
return Optional.empty();
}
}
5. Custom enum labels
Sometimes enum names are not the same as external values. In that case, valueOf() is not enough.
public enum Status {
ACTIVE("active"),
INACTIVE("inactive");
private final String label;
Status(String label) {
this.label = label;
}
public String getLabel() {
return label;
}
public static Status fromLabel(String text) {
for (Status status : values()) {
if (status.label.equalsIgnoreCase(text)) {
return status;
}
}
throw new IllegalArgumentException("Unknown status: " + text);
}
}
This pattern is common when input strings are human-friendly or come from external formats.
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:
Blah value = Blah.valueOf(" A ".trim());
3. Not handling invalid input
Broken code:
String input = userInput();
Blah value = Blah.valueOf(input);
Problem:
- if the input is invalid, the program throws
IllegalArgumentException
Fix:
try {
Blah value = Blah.valueOf(input);
} catch (IllegalArgumentException e) {
System.out.println("Invalid value");
}
4. Passing null
Broken code:
String input = null;
Blah value = Blah.valueOf(input);
Problem:
- this throws
NullPointerException
Fix:
if (input != null) {
Blah value = Blah.valueOf(input);
}
5. Assuming valueOf() uses custom labels
If your enum looks like this:
public enum Status {
ACTIVE("active");
private final String label;
Status(String label) {
this.label = label;
}
}
Then this will not work:
Status s = Status.valueOf("active");
Why?
valueOf()matches the enum constant name, which isACTIVE- it does not match the field value
"active"
Fix:
- use
Status.valueOf("ACTIVE") - or write a custom lookup method
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")) ... | Rare cases | Usually more verbose and harder to maintain |
valueOf() vs custom lookup
| Feature | valueOf() | Custom method |
|---|---|---|
| Exact name match | Yes | Optional |
| Case-insensitive matching | No | Yes, if you implement it |
| Handles spaces automatically | No | Yes, if you implement it |
| Matches custom labels | No | Yes |
| Built into Java | Yes | No |
When to use which
- Use
Blah.valueOf()when input already matches enum constant names. - Use a custom method when input comes from users, files, APIs, or other unreliable sources.
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 {
return Blah.valueOf(input.trim().toUpperCase());
} catch (IllegalArgumentException e) {
return null;
}
}
Remember
"A"-> works"a"-> fails unless normalized" A "-> fails unless trimmed"Z"-> fails
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()?
No. valueOf() only matches the enum constant name, such as ACTIVE. For custom labels, write a separate lookup method.
Should I use enums instead of strings in Java?
Usually yes, when the value comes from a fixed set of known options. Enums are safer, clearer, and easier to maintain than raw strings.
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
Add External JAR Files to an IntelliJ IDEA Java Project
Learn how to add external JAR dependencies to an IntelliJ IDEA Java project using module libraries, and when to use Maven or Gradle instead.
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.
Call a Method After a Delay in Android Java
Learn how to run Java code after a delay in Android using Handler.postDelayed, manage the main thread, and cancel callbacks safely.