Java enum Strings
In this tutorial, we will learn about string values for enum constants. We will likewise learn to override default string value for enum constants with the help of examples.
Java enum Strings
Before you learn about enum strings, make sure to know about Java enum.
In Java, we can get the string portrayal of enum constants using the toString() method or the name() technique. For instance,
enum Size {
SMALL, MEDIUM, LARGE, EXTRALARGE
}
class Main {
public static void main(String[] args) {
System.out.println("string value of SMALL is " + Size.SMALL.toString());
System.out.println("string value of MEDIUM is " + Size.MEDIUM.name());
}
}
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,
enum Size {
SMALL {
// overriding toString() for SMALL
public String toString() {
return "The size is small.";
}
},
MEDIUM {
// overriding toString() for MEDIUM
public String toString() {
return "The size is medium.";
}
};
}
class Main {
public static void main(String[] args) {
System.out.println(Size.MEDIUM.toString());
}
}
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.
Thanks for reading! We hope you found this tutorial helpful and we would love to hear your feedback in the Comments section below. And show us what you’ve learned by sharing your photos and creative projects with us.