Java Program to Lookup enum by String value


In this article, we will understand how to lookup enum by string value. An enum is a special "class" that represents a group of constants (unchangeable variables, like final variables).

Below is a demonstration of the same −

Suppose our input is

The string is to lookup is: Java

The desired output would be

The result is:
JAVA

Algorithm

Step 1 - START
Step 2 - Declare a string namely input_string, an object of Languages namely result.
Step 3 - Define the values.
Step 4 - Use the function .valueOf() to fetch the string from the enum function.
Step 5 - Display the result
Step 6 - Stop

Example 1

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

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 is to lookup is: Java

The result is:
JAVA

Example 2

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

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: 30-Mar-2022

521 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements