
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How can we get the name of the Enum constant in Java?
In Java, an Enum is a class or special datatype that defines a collection of constants. It was introduced in Java version 1.5. When we need a predefined list of values that do not represent numeric or textual data, we can use an Enum class.
Enums are constants, which means their fields are implicitly public, static, and final by default. The names of enum constants are written in uppercase letters. Following is the syntax to create an Enum in Java:
Enum enumName{ CONST_VALUE1, CONST_VALUE2, CONST_VALUE3....CONST_VALUEN; }
Retrieving Name of the Enum Constant
The java.lang.Enum class provides various methods to access and manipulate the constants in an enumeration object. Here are the various ways to get the name of an enum constant:
Using Enum name() Method
The name() method of the Enum class is used to retrieve the name of the current enum constant. Following is the syntax of this method:
Shape.name()
Example
The following example uses the Enum name() method to retrieve the name of the enum constant:
//enum enum Shape { CIRCLE, TRIANGLE, SQUARE, RECTANGLE; } public class EnumNameTest { public static void main(String[] args) { Shape shape = Shape.RECTANGLE; //using name() method System.out.println("The name of an enum constant is: " + shape.name()); } }
The above program displays the name of the enum constant:
The name of an enum constant is: RECTANGLE
Using valueOf() Method
The valueOf() method of the Enum class is used to retrieve the enum constant of the specified enum type with the specified name (as a string).
It is case-sensitive and throws an IllegalArgumentException if the name doesn't match any constant. Following is the syntax of the valueOf() method:
valueOf(Class<T> enumType, String name)
Here, enumType is the Class object of the enum type from which to return a constant, and name is the name of the constant to be returned.
Example
The following is an example of retrieving an enum constant using the valueOf() method.
//enum enum Shape { CIRCLE, TRIANGLE, SQUARE, RECTANGLE; } public class EnumNameTest { public static void main(String[] args) { //using valueOf() method Shape shape = Shape.valueOf("CIRCLE"); System.out.println("The name of the enum constant is: " + shape); } }
Following is the output of the above code:
The name of the enum constant is: CIRCLE