Lookup Enum by String Value in Java



In this article, we will understand how to look up enum by string value using Java. An enum is a special "class" that represents a group of constants (unchangeable variables, like final variables). The program will demonstrate how you can convert a string to its corresponding enum value using the valueOf() method, as well as how to print enum values using the enum name() method.

Problem Statement

Write a program in Java to look up enum by string value. Below is a demonstration of the same ?

Input

The string to lookup is: Java

Output

The result is: JAVA

Different Approaches

Following are the different approaches to look up enum by string value ?

Enum lookup using valueOf()

Following are the steps to look up an enum by string value using valueOf() ?

  • First, we will declare an enum called Languages with constants.
  • After that, we will create a string variable that contains the input value (e.g., "Java").
  • Convert the input string to uppercase using the toUpperCase() method.
  • We will be using the valueOf() method of the Languages enum to match the uppercase string with the enum value.
  • Print the matched enum value.

Example

Here, we use valueOf() to print the enum values ?

Open Compiler
public class Demo { public enum Languages { JAVA, SCALA, PYTHON, MYSQL } public static void main(String[] args) { String input_string = "Java"; System.out.println("The string is to lookup is: " +input_string); Languages result = Languages.valueOf(input_string.toUpperCase()); System.out.println("\nThe result is: "); System.out.println(result); } }

Output

The string to lookup is: Java

The result is:
JAVA

Printing enum values with .name()

Following are the steps to print enum values using the .name() method ?

  • First, we will declare an enum called Languages with constants.
  • Print a message indicating that you will display all enum values.
  • Use the .name() method to print each enum value in its string form.
  • Display the enum values one by one.

Example

Here, we use the .name() function to print the ENUM values ?

Open Compiler
enum Languages { Java, Scala, Python, Mysql; } public class Demo { public static void main(String[] args) { System.out.println("The values of the ENUM are: "); System.out.println(Languages.Java.name()); System.out.println(Languages.Scala.name()); System.out.println(Languages.Python.name()); System.out.println(Languages.Mysql.name()); } }

Output

The values of the ENUM are:
Java
Scala
Python
Mysql
Updated on: 2024-10-21T11:06:00+05:30

739 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements