Java Enum toString() Method
Example
Get the name of an enum constant as text:
public class Main {
enum Level { LOW, MEDIUM, HIGH }
public static void main(String[] args) {
Level myVar = Level.MEDIUM;
System.out.println(myVar.toString());
System.out.println("The level is " + myVar);
}
}
Definition and Usage
The toString() method returns the name of the enum constant as a String, for example "MEDIUM". Java calls it automatically when you print a constant, or join it with a string.
You can override toString() (write your own version of it in the enum) to return a friendlier text, for example "Medium level".
Tip: Use name() when you need the exact name of the constant, even if toString() is overridden.
Syntax
public String toString()
Parameter Values
None.
Technical Details
| Returns: | The name of the constant, or the text that your own toString() returns. |
|---|
Related Pages
Java Enum Constructor Tutorial
❮ Enum Methods