Monday, December 30, 2024
Google search engine
HomeLanguagesJavaJava Program to Convert Enum to String

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. 

  • 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




// 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.

  • 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




// 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
Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments