Tuesday, January 14, 2025
HomeProgrammingHow can you retrieve an enum value from a string in Java?

How can you retrieve an enum value from a string in Java?

To get an enum value from a string in Java, you can use the valueOf() method provided by the enum class. This method converts a string to the corresponding enum constant. Here’s an example:

public enum Color {
RED, GREEN, BLUE;
}

See also  terminology - What does Buffer Mean?

String colorName = “GREEN”;
Color color = Color.valueOf(colorName); // Returns Color.GREEN

If the string does not match any enum constant, valueOf() will throw an IllegalArgumentException. To avoid this, you can use a try-catch block or the EnumUtils.getEnum() method from Apache Commons Lang for safer handling.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x