Open In App

Java Program to Convert Enum to String

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:



  1. Using name() Method
  2. 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. 

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 is used to get a string object which represents the value of the number 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

Article Tags :