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,


\begin{lstlisting}
enum Size {
SMALL, MEDIUM, LARGE, EXTRALARGE
}
\par
class Ma...
...(''string value of MEDIUM is '' + Size.MEDIUM.name());
\par
}
}
\end{lstlisting}

The output for the above code block is going to be


\begin{lstlisting}
string value of SMALL is SMALL
string value of MEDIUM is MEDIUM
\end{lstlisting}

In the above example, we have seen the default string representation of an enum constant is the name of the same constant. We can change the default string representation of enum constants by overriding the toString() method. For example,


\begin{lstlisting}
enum Size {
SMALL {
\par
// overriding toString() for SMALL
...
...ing[] args) {
System.out.println(Size.MEDIUM.toString());
}
}
\end{lstlisting}

The output for above code will be 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. We cannot override the name() method. It is because the name() method is final.