To 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":
enum Color {
RED, GREEN, BLUE
}
public class Main {
public static void main(String[] args) {
String colorString = "RED";
Color color = Color.valueOf(colorString);
System.out.println(color); // 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:
enum Color {
RED, GREEN, BLUE
}
public class Main {
public static void main(String[] args) {
String colorString = "YELLOW";
Color color;
try {
color = Color.valueOf(colorString);
} catch (IllegalArgumentException e) {
System.out.println("The color '" + colorString + "' is not a valid color.");
}
System.out.println(color); // null
}
}
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.
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
To 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.