![]() |
VOOZH | about |
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.
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;GREEN
To know more about Enum, refer to Enum in Java article.
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.
EnumType.valueOf(String name)
Converted color: RED Invalid color string: YELLOW
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.
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:
Match found: Person Details : name : 'John' gender : MALE age : 30.