Converting a String to an Enum in Java

In Java, an enumeration, commonly known as Enum, is a special data type that allows us to define a fixed set of named values or constants. Enums provide a way to represent a predefined list of elements with distinct identifiers and it makes our code more readable and maintainable.

In this article, we will learn how to convert a string into an enum type.

Basic Understanding of Java Enum

Before diving into the String to Enum conversion, a basic understanding of Java enum is required. Here is an example of simple enum code to define enum types and declare constants within enums.

public enum Color{
      RED, GREEN, BLUE
}

We can access enum constants with a dot syntax.

Color myCol = Color.GREEN;

How to define enum inside as a class?

Java




import java.io.*;
  
class GFG {
      enum Color{
        RED, GREEN, BLUE
    }
    public static void main (String[] args) 
    {
      Color myCol = Color.GREEN;
        System.out.println(myCol);
    }
}


Output

GREEN


To know more about Enum, refer to Enum in Java article.

Method to convert Strings to Enums in Java

To convert a string to an enum we will use valueOf() method.

ValueOf(): In java, the valueOf() method is a static method that belongs to the enum class. It is automatically generated by the compiler for all enum types. The primary purpose of the valueOf() method is to convert a string to enum.

Syntax:

EnumType.valueOf(String name)
  • EnumType: The enum type for which we want to obtain an enum constant.
  • name: The name of the enum constant as a string.

Implementation:

Java




// Java program to convert a string to enum
import java.io.*;
import java.util.Scanner;
  
// Creating an enum constant string
enum Color {
    RED, GREEN, BLUE
}
class GFG {
    public static Color convertStringToEnum(String colorString) {
        try {
            return Color.valueOf(colorString);
              // When the input string matches the enum constant, for example, here we type either RED
            // or GREEN or BLUE
        } catch (IllegalArgumentException e) {
            // Handle the case when the input String doesn't match any enum constant
            // For example, we might want to return a default value or throw a more meaningful exception.
            System.out.println("Invalid color string: " + colorString);
            return null;
        }
    }
  
    public static void main(String[] args) {
        // Valid conversion
        Color redColor = convertStringToEnum("RED");
        System.out.println("Converted color: " + redColor);
  
        // Invalid conversion
        Color invalidColor = convertStringToEnum("YELLOW");
        // This will print an error message from the catch block in the convertStringToEnum method.
    }
      
}


Output

Converted color: RED
Invalid color string: YELLOW


Explanation of the above Program:

  • The color enum is defined with constants: RED, GREEN and BLUE.
  • The GFG class contains a method named convertStringToEnum that takes a string parameter(colorStrings) and attempts to convert it to a Color enum using the valueOf() method.
  • The main method demonstrates the usage of the conversion method eith both a valid string and invalid string.
  • In the output, the first line illustrates the successful conversion of a valid string to an enum(RED), and the second line is handling an invalid string that does not match any enum constant.

Another Example

Write a Java program to convert a string to enum. Each string will include name of the person, their gender and age. If the input matches the name with the input, then the program will show gender and age of that person.

Approach:

To solve this problem, we can create a custom enum Person with attributes like name, gender and age. Then implement the methods that takes a string input, and searches for a matching name, and returns the corresponding output.

Below is the implementation of Converting a String to an Enum in Java:

Java




// Java Program to Convert a String to Enum
import java.util.Arrays;
  
// Enum representing different persons
enum Person {
    // Enum constants with attributes: name, gender, and age
    JOHN("John", Gender.MALE, 30),
    MARY("Mary", Gender.FEMALE, 25),
    MIKE("Mike", Gender.MALE, 35);
  
    private final String name;
    private final Gender gender;
    private final int age;
  
    // Constructor to initialize enum constants with
    // attributes
    Person(String name, Gender gender, int age)
    {
        this.name = name;
        this.gender = gender;
        this.age = age;
    }
  
    // Getter method for name
    public String getName() { return name; }
  
    // Getter method for gender
    public Gender getGender() { return gender; }
  
    // Getter method for age
    public int getAge() { return age; }
  
    // Override toString() method for better output
    // representation
    @Override public String toString()
    {
        return "Person Details : \n"
            + "name : '" + name + '\'' + "\ngender : "
            + gender + "\nage : " + age + '.';
    }
}
  
// Enum representing gender
enum Gender { MALE, FEMALE }
  
// Main class
public class GFG {
    // Main Function
    public static void main(String[] args)
    {
        // Example input (you can get this from user input)
        String userInput = "John";
  
        try {
            // Use valueOf directly to convert the input
            // String to a Person enum
            // Convert to uppercase for case-insensitive
            // comparison
            Person matchedPerson
                = Person.valueOf(userInput.toUpperCase());
  
            // Display the result
            System.out.println("Match found:\n"
                               + matchedPerson.toString());
        }
        catch (IllegalArgumentException e) {
            System.out.println(
                "No matching person found for input: "
                + userInput);
        }
    }
}


Output

Match found:
Person Details : 
name : 'John'
gender : MALE
age : 30.


Explanation of the above Program:

  • The person enum represents individuals with attributes like name, gender and age.
  • The Gender enum representing gender with constants MALE and FEMALE.
  • Next is the main class: The user provides input, which s name of a person.
  • Then the valueOf() method directly to convert the input string to a person enum.
  • The next, it displays details (name, gender and age) of the matched person. Also handles the case when the input string does not match any enum constant using a try-catch block.