Before knowing about Enum Strings, you must be familiar with Enums in Java.
String enums are similar to numeric enums, except that the enum values are initialized with string values rather than numeric values. The benefit of using string enums is that string enums are more readable and easy to debug.
In Java, we have two ways to convert Enum to String first by using the name() method of Enum which is an implicit method and available to all Enum, and second by using the toString() method.
Example with name() and toString() :
Code:
Java Code
enum Size {
MEDIUM, LARGE, EXTRALARGE
}
enum PrintMedia {
Newspaper,
Magazine ,
Book ,
}
class Main {
public static void main(String[] args) {
System.out.println("string value of Size is " +
PrintMedia.Newspaper.toString());
System.out.println("string value of PrintMedia is " +
PrintMedia.Magazine.name());
}
}
Output:
string value of Size is Newspaper
string value of PrintMedia is Magazine
How can we change the value of the string in the enum?
We can override the toString() method and change the default values:
Code:
Java Code
enum Size {
STUDENT {
// overriding toString() for STUDENT
public String toString() {
return "STUDENT";
}
},
TEACHER {
// overriding toString() for TEACHER
public String toString() {
return "TEACHER";
}
};
}
class Main {
public static void main(String[] args) {
System.out.println(Size.TEACHER.toString());
System.out.println(Size.STUDENT.toString());
}
}
Output:
TEACHER
STUDENT
In the above example, we have created two enums one for TEACHER and another one for STUDENT. And we have overridden these two enum constants using the toString() method.
Point to note here :
We can not override the enum string using the name(), because it is considered as final.
Special thanks to Amisha Kumari for contributing to this article on takeUforward. If you also wish to share your knowledge with the takeUforward fam, please check out this article