Java Enum name() Method
Example
Get the name of an enum constant as a String:
public class Main {
enum Level { LOW, MEDIUM, HIGH }
public static void main(String[] args) {
Level myVar = Level.HIGH;
System.out.println(myVar.name());
System.out.println(myVar.name().toLowerCase());
}
}
Definition and Usage
The name() method returns the name of the enum constant as a String, exactly as it is written in the enum, for example "HIGH".
Most of the time, toString() returns the same text. The difference is that toString() can be overridden (replaced with your own version in the enum), while name() always returns the real name.
Tip: Use valueOf() to do the opposite: get the constant from its name.
Syntax
public final String name()
Parameter Values
None.
Technical Details
| Returns: | The name of the constant, as a String. |
|---|
Related Pages
Java Enum Constructor Tutorial
❮ Enum Methods