Given an enum containing a gaggle of constants, the task is to convert the enum to a String.
Methods:
We can solve this problem using two methods:
Let us discuss both of them intimately and implementing them to urge a far better understanding of an equivalent.
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 need to print it.
The value given inside is first the name of the enum class that we'll create further, then calling the constant that's named, finally using the name() method.
Now create another java enum file named Fruits.java within the same folder where you created the most file, and declare the enum as follows:
Example
public enum Fruits { Orange, Apple, Banana, Mango; }
// Java Program to Convert Enum to String // using // Importing input output classes import java.io.*; // Enum enum Fruits { Orange, Apple, Banana, Mango; } // Main class class GFG { // Main driver method public static void main(String[] args) { // Printing all the values 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's wont to get a string object which represents the worth of the amount object.
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 Program to Convert Enum to String // Using toString() Method // Importing input output classes import java.io.*; // Enum enum Fruits { // Custom entries Orange, Apple, Banana, Mango; } // Main class class Main { // Main driver method public static void main (String[] args) { // Printing all the values 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
Australia
UK
UAE
Singapore
Canada
New
Zealand
Malaysia
USA
India
South
Africa
Ireland
Saudi
Arab
Qatar
Kuwait
Hongkong
Copyright 2016-2023 www.programmingshark.com - All Rights Reserved.
Disclaimer : Any type of help and guidance service given by us is just for reference purpose. We never ask any of our clients to submit our solution guide as it is, anywhere.