How to get an enum value from a string value in Java?
How to get an enum value from a string value in Java?
128
21-Jul-2023
Aryan Kumar
22-Jul-2023To get an enum value from a string value in Java, you can use the valueOf() method of the enum type. The valueOf() method takes a string as a parameter and returns the enum constant that has the same name as the string.
For example, the following code gets the enum value for the string "RED":
If the string does not match any of the enum constants, the valueOf() method will throw an IllegalArgumentException.
Here is an example of how to handle an IllegalArgumentException in Java:
As you can see, the valueOf() method is a convenient way to get an enum value from a string value. However, it is important to handle the IllegalArgumentException that it can throw.