dsa

Java enum Strings

In this tutorial, we will learn to learn about string values for enum constants. We will also learn to override default string value for enum constants with the help of examples.

In this guide to Java enum with string values, learn to create enum using strings, iterate over all enum values, get enum value and to perform reverse lookup to find enum by string parameter. In a string enum, each member has to be constant-initialized with a string literal, or with another string enum member.
In Java, we can get the string representation of enum constants using the toString() method or the name() method.
For example,

enum Day {
   SUNDAY, MONDAY, TUESDAY
}

class Main {
   public static void main(String[] args) {

      System.out.println("string value of SUNDAY is " + Day.SUNDAY.toString());
      System.out.println("string value of MONDAY is " + Day.MONDAY.name());
}
}
Output

string value of SUNDAY is SUNDAY
string value of MUNDAY is MUNDAY

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 Day {
   SUNDAY {

      // overriding toString() for SUNDAY
      public String toString() {
        return "The day is sunday.";
      }
   },

   MONDAY {

     // overriding toString() for MONDAY
      public String toString() {
        return "The day is monday.";
      }
   };
}

class Main {
   public static void main(String[] args) {
      System.out.println(Day.MONDAY.toString());
   }
}
Output

The day is monday.
       

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