Java enum Strings

Java enum Strings

Before you learn about enum strings, make sure to know about Java enum.

In Java, we can get the string representation of enum constants using the toString() method or the name() method. For example,

Output

string value of SMALL is SMALL
string value of MEDIUM is MEDIUM

In the above example, we have seen the default string representation of an enum constant is the name of the same constant.


Change Default String Value of enums

We can change the default string representation of enum constants by overriding the toString() method. For example,

Output

The size is medium.

In the above program, we have created an enum Size. And we have overridden the toString() method for enum constants SMALL and MEDIUM.

Note: We cannot override the name() method. It is because the name() method is final.

To learn more, visit best ways to create enum String.