Java Enum valueOf() Method
Example
Get an enum constant from its name:
public class Main {
enum Level { LOW, MEDIUM, HIGH }
public static void main(String[] args) {
Level myVar = Level.valueOf("HIGH");
System.out.println(myVar);
System.out.println(myVar == Level.HIGH);
}
}
Definition and Usage
The valueOf() method returns the enum constant that has the given name. For example, Level.valueOf("HIGH") returns Level.HIGH.
You do not write this method yourself. The Java compiler adds it to every enum that you create. The name must match exactly, also uppercase and lowercase letters. If no constant has that name, the method throws an IllegalArgumentException.
Tip: If the name can be wrong, for example when it comes from user input, call valueOf() inside a try block and catch the IllegalArgumentException.
Syntax
public static E valueOf(String name)
E refers to the enum type, for example Level.
Parameter Values
| Parameter | Description |
|---|---|
| name | Required. The exact name of the constant, for example "HIGH". |
Technical Details
| Returns: | The enum constant with the given name. |
|---|---|
| Throws: | IllegalArgumentException - if the enum has no constant with this name. |
Related Pages
Java Enum Constructor Tutorial
❮ Enum Methods