Open In App

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?




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)

Implementation:




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

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 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:


Article Tags :