1. Introduction
In Java, Enums are a type of class that represents a group of named constants. Converting a String to an Enum is a common task, especially when dealing with user inputs or external data sources. Java provides a method Enum.valueOf() that allows us to convert a String to an Enum of the specified type.
2. Program Steps
1. Define an Enum with some constants.
2. Define a main method inside a Java class.
3. Declare a String variable containing one of the Enum constants’ names.
4. Use the Enum.valueOf() method to convert the String to an Enum constant.
5. Print the original String and the converted Enum constant.
3. Code Program
// Step 1: Define an Enum with some constants
enum Days {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
}
public class StringToEnum {
public static void main(String[] args) {
// Step 3: Declare a String variable containing one of the Enum constants' names
String dayString = "WEDNESDAY";
// Step 4: Use the Enum.valueOf() method to convert the String to an Enum constant
Days dayEnum = Enum.valueOf(Days.class, dayString);
// Step 5: Print the original String and the converted Enum constant
System.out.println("Original String: " + dayString);
System.out.println("Converted Enum: " + dayEnum);
}
}
Output:
Original String: WEDNESDAY Converted Enum: WEDNESDAY
4. Step By Step Explanation
– Step 1: An Enum named Days is defined with constants representing the days of the week.
– Step 2: The main method is defined inside a class named StringToEnum.
– Step 3: A String variable dayString is declared containing the name of one of the Enum constants.
– Step 4: The Enum.valueOf() method is used to convert dayString to a constant of Enum type Days. The result is stored in the variable dayEnum.
– Step 5: The original String dayString and the converted Enum constant dayEnum are printed to the console.
By using Enum.valueOf(), this program demonstrates how to convert a String to a corresponding Enum constant in Java.