How to Use Enum valueOf Method in Java
In Java, use
EnumType.valueOf(String name) to convert a string to its matching enum constant. The string must exactly match the enum constant's name, or it throws an IllegalArgumentException. This method helps convert text input into enum values.Syntax
The valueOf method is a static method of an enum type that takes a String argument representing the name of the enum constant.
EnumType.valueOf(String name): Returns the enum constant of the specified enum type with the specified name.- The
namemust match exactly an identifier used to declare an enum constant in this type.
java
EnumType.valueOf(String name)Example
This example shows how to convert a string to an enum constant using valueOf. It prints the enum constant and its ordinal position.
java
public class EnumValueOfExample { enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY } public static void main(String[] args) { String input = "WEDNESDAY"; Day day = Day.valueOf(input); System.out.println("Enum constant: " + day); System.out.println("Ordinal position: " + day.ordinal()); } }
Output
Enum constant: WEDNESDAY
Ordinal position: 2
Common Pitfalls
Common mistakes when using valueOf include:
- Passing a string that does not exactly match any enum constant name causes
IllegalArgumentException. - Enum names are case-sensitive, so "monday" will fail if the enum constant is "MONDAY".
- Passing
nullthrowsNullPointerException.
To avoid errors, validate input or use try-catch to handle exceptions.
java
public class EnumValueOfPitfall { enum Color { RED, GREEN, BLUE } public static void main(String[] args) { try { String input = "green"; // lowercase, will cause exception Color color = Color.valueOf(input); } catch (IllegalArgumentException e) { System.out.println("Invalid enum constant: " + e.getMessage()); } } }
Output
Invalid enum constant: No enum constant EnumValueOfPitfall.Color.green
Quick Reference
- Method:
EnumType.valueOf(String name) - Input: Exact name of enum constant (case-sensitive)
- Returns: Enum constant matching the name
- Throws:
IllegalArgumentExceptionif no match,NullPointerExceptionifnull - Use case: Convert string input to enum safely
Key Takeaways
Use
EnumType.valueOf(String) to convert a string to an enum constant.The string must exactly match the enum constant name, including case.
Handle
IllegalArgumentException to catch invalid inputs safely.Passing
null to valueOf causes NullPointerException.Use
valueOf to map text input to enum values in your programs.