Converting a String to an Enum in Java
Last Updated :
13 Feb, 2024
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);
}
}
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.
}
}
OutputConverted 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);
}
}
}
OutputMatch 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.
Similar Reads
How to Convert a String to an Long in Java ?
In Java, String to Integer Conversion is not always effective as the size of the String can overpass Integer. In this article, we will learn the method provided by the Long class or by using the constructor of the Long class. Example of String to Long ConversionInput: " 9876543210"Output: 9876543210
2 min read
How to convert an Array to String in Java?
In Java, there are different ways to convert an array to a string. We can choose ways from built-in methods or custom approaches, depending on the type of arrays. Using Arrays.toString()The most simple method is the Arrays.toString() to convert an array to a string. Example: [GFGTABS] Java // Java P
1 min read
How to Convert a String to a UUID in Java?
A Universally Unique Identifier (UUID) is a 128-bit label utilised for information in computer systems. The term Globally Unique Identifier (GUID) is also used especially in Microsoft systems. UUIDs are regularised by the Open Software Foundation (OSF) as part of the Distributed Computing Environmen
2 min read
How to Convert a String to a Path in Java?
In Java, we can convert a String representation of a file or directory path into a path object using the Paths utility class. It is a part of the java.nio.file package. The Paths class provides a method called get(String file path location) that converts a sequence of strings representing a path int
2 min read
How to Convert Char to String in Java?
In this article, we will learn how to Convert Char to String in Java. If we have a char value like 'G' and we want to convert it into an equivalent String like "G" then we can do this by using any of the following three listed methods in Java. Using toString() method of Character classUsing valueOf(
5 min read
How to Convert a String to an Numeric in Java?
In Java programming, there are situations in which we must convert a string of numeric characters into one of the following data types: double, float, long, or int. To execute arithmetic operations and other numerical calculations, this conversion is necessary. We will look at how to convert a strin
2 min read
How to Convert a String to URL in Java?
In Java, a string is a sequence of characters. A URL, which is short for Uniform Resource Locator, refers to a web resource that specifies its location on a computer network and provides the mechanism for retrieving it. To represent a URL in Java, we use the java.net.URL class. In this article, we w
2 min read
Convert a String to a ByteBuffer in Java
In Java, ByteBuffer can be used to perform operations at the Byte level one more thing is this class provides different types of methods for reading writing, and manipulating bytes in a structured way only. In this article, we will learn about String to ByteBuffer in Java. Java Program to Convert St
4 min read
How to Convert a String to ArrayList in Java?
Converting String to ArrayList means each character of the string is added as a separator character element in the ArrayList. Example: Input: 0001 Output: 0 0 0 1 Input: Geeks Output: G e e k s We can easily convert String to ArrayList in Java using the split() method and regular expression. Paramet
1 min read
Convert a String to Character Array in Java
Converting a string to a character array is a common operation in Java. We convert string to char array in Java mostly for string manipulation, iteration, or other processing of characters. In this article, we will learn various ways to convert a string into a character array in Java with examples.
2 min read