English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this tutorial, we will learn about the string values of enum constants. We will also learn how to rewrite the default string value of enum constants with examples.
Before learning about enum strings, make sure you have already understoodJava Enum.
In Java, we can use the toString() or name() method to obtain the string representation of enum constants. For example,
enum Size {}} SMALL, MEDIUM, LARGE, EXTRALARGE } class Main { public static void main(String[] args) { System.out.println("The string value of SMALL is "); + Size.SMALL.toString()); System.out.println("The string value of MEDIUM is "); + Size.MEDIUM.name()); } }
Output Result
The string value of SMALL is SMALL The string value of MEDIUM is MEDIUM
In the above example, we have already seen that the default string representation of enum constants is the name of the same constant.
We can change the default string representation of enum constants by rewriting the toString() method. For example,
enum Size {}} SMALL { //Override toString() as SMALL public String toString() { return "The size is small."; } }, MEDIUM { //Override toString() as MEDIUM public String toString() { return "The size is medium."; } }; } class Main { public static void main(String[] args) { System.out.println(Size.MEDIUM.toString()); } }
Output Result
The size is medium.
In the above program, we have created an enum Size. And we have overridden the toString() method of enum constants SMALL and MEDIUM.
Note:We cannot override the name() method. This is because the name() method is of final type.