1. Introduction
Enums in Java are used to represent a group of named constants, making the code more readable and reducing the possibility of errors. Converting an Enum to a String is quite straightforward in Java, as the Enum class has a toString() method that returns the name of this enum constant, as contained in the declaration.
2. Program Steps
1. Define an Enum with some constants.
2. Inside the main method of a Java class, create a variable of the Enum type and assign it one of the constants.
3. Convert the Enum constant to a String using the toString() method.
4. Print both the Enum constant and the converted String to the console.
3. Code Program
// Step 1: Define an Enum with some constants
enum Color {
RED, GREEN, BLUE;
}
public class EnumToString {
public static void main(String[] args) {
// Step 2: Create a variable of the Enum type and assign it one of the constants
Color colorEnum = Color.GREEN;
// Step 3: Convert the Enum constant to a String using the toString() method
String colorString = colorEnum.toString();
// Step 4: Print both the Enum constant and the converted String to the console
System.out.println("Original Enum: " + colorEnum);
System.out.println("Converted String: " + colorString);
}
}
Output:
Original Enum: GREEN Converted String: GREEN
4. Step By Step Explanation
– Step 1: An Enum named Color is defined with constants representing different colors.
– Step 2: A variable colorEnum of Enum type Color is declared and assigned one of the constants from the Color Enum.
– Step 3: The toString() method is used to convert colorEnum to a String, which is stored in the variable colorString.
– Step 4: The original Enum constant colorEnum and the converted String colorString are printed to the console.
By using the toString() method of the Enum class, this program easily converts an Enum constant to its String representation.