How can we get the name of the Enum constant in Java?

JavaObject Oriented ProgrammingProgramming

An Enum is a special datatype which is added in Java 1.5 version and it can be used to define a collection of constants, when we need a predefined list of values that do not represent some kind of numeric or textual data, we can use an Enum. The enums are constants and by default, they are static and final, so the names of an enum type fields are in uppercase letters.

The name of the enum constant is returned by the method java.lang.Enum.name(). This method returns the name exactly as it was declared in the enum declaration.

Example

enum Shape {
CIRCLE, TRIANGLE, SQUARE, RECTANGLE;
}
public class EnumNameTest {
   public static void main(String[] args) {
      Shape shape = Shape.RECTANGLE;
      System.out.println("The name of an enum constant is: " + shape.name());
   }
}

Output

The name of an enum constant is: RECTANGLE
raja
Published on 04-Sep-2019 11:47:35
Advertisements