Given an enum containing a group of constants, the task is to convert the enum to a String.

Methods:
We can solve this problem using two methods:
- Using name() Method
- Using toString() Method
Let us discuss both of them in detail and implementing them to get a better understanding of the same.
Method 1: Using name() Method
It returns the name of the enum constant same as declared in its enum declaration.
- We would be using name() method to return the name of the enum constant.
- In the main class, we just have to print it.
- The value given inside is first the name of the enum class that we will create further, then calling the constant that is named, finally using the name() method.
- Now create another java enum file named Fruits.java in the same folder where you created the main file, and declare the enum as follows:
Example
public enum Fruits {
Orange, Apple, Banana, Mango;
}
Java
import java.io.*;
enum Fruits {
Orange,
Apple,
Banana,
Mango;
}
class GFG {
public static void main(String[] args) {
System.out.println(Fruits.Orange.name());
System.out.println(Fruits.Apple.name());
System.out.println(Fruits.Banana.name());
System.out.println(Fruits.Mango.name());
}
}
|
Output
Orange
Apple
Banana
Mango
Method 2: Using toString() Method
It is used to get a string object which represents the value of the number object.
- We will be following the same procedure as earlier used but the only difference here is that we will be using toString() method. So just replace name() method with toString() method.
Note: Do not forgot to create a Fruits.java enum file in the same folder.
Illustration:
public enum Fruits {
Orange, Apple, Banana, Mango;
}
Example 2
Java
import java.io.*;
enum Fruits {
Orange,
Apple,
Banana,
Mango;
}
class Main {
public static void main (String[] args) {
System.out.println(Fruits.Orange.toString());
System.out.println(Fruits.Apple.toString());
System.out.println(Fruits.Banana.toString());
System.out.println(Fruits.Mango.toString());
}
}
|
Output
Orange
Apple
Banana
Mango
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!