Java.lang Package Classes

Java Enum - toString() Method



The java.lang.Enum.toString() method returns the name of this enum constant, as contained in the declaration.

Syntax

public String toString()

Parameters

No parameter is required.

Return Value

Returns the name of this enum constant.

Exception

NA.

Example:

In the example below, the java.lang.Enum.toString() method returns the name of the given enum.

import java.lang.*;

public class MyClass {
  
  //creating an enum
  public enum WeekDay{
    MON("1st"), TUE("2nd"), WED("3rd"), THU("4th"), FRI("5th");

    String day;
    WeekDay(String x) {
      day = x;
    }

    String showDay() {
      return day;
    }
  }

  public static void main(String[] args) {
    System.out.println("WeekDay List:");
    for(WeekDay i : WeekDay.values()) {
      System.out.println(i + " is the " + i.showDay() + " day of the week.");
    }

    WeekDay val = WeekDay.MON;
    System.out.println("WeekDay Name = " + val.toString()); 

  }
}

The output of the above code will be:

WeekDay List:
MON is the 1st day of the week.
TUE is the 2nd day of the week.
WED is the 3rd day of the week.
THU is the 4th day of the week.
FRI is the 5th day of the week.
WeekDay Name = MON

❮ Java.lang - Enum