Sunday, May 22, 2022

Converting String to Enum Type in Java

There may be a scenario where a string is passed in your code and you have to convert that string into enum type in Java. For that you can use valueOf() method which is implicitly created for all enums.

public static T valueOf(String str)– This method is used to map from a String str to the corresponding enum constant. The name must match exactly an identifier used to declare an enum constant in this type.

If no constant with in the enum is found that matches the string passed IllegalArgumentException is thrown.

So, in order to convert String to enum in Java, the passed string should match one of the predefined constants in the enum. Actually it is not conversion in a true sense but you are searching for the enum type with the same name as the passed string, value returned is of type enum though.

Java Example code converting string to enum

 
enum Day {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
    THURSDAY, FRIDAY, SATURDAY 
} 
public class EnumDemo {

 public static void main(String[] args) {
  EnumDemo ed = new EnumDemo();
  ed.lookUp("tuesday");
  
 }
 
 // method to lookup ennum constants
 public void lookUp(String str){
  Day day = Day.valueOf(str.toUpperCase());
  System.out.println("Found enum " + day );
 }
}

Output

 
Found enum TUESDAY

Here you can see that a string "Tuesday" is passed and using valueOf() method you get the corresponding enum constant. Make sure the name is same (that is why converted string to uppercase) not even extraneous whitespace are permitted. Use trim() method if you think there may be extraneous white spaces in the string passed.

That's all for this topic Converting String to Enum Type in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Comparing Enum to String in Java
  2. Convert String to int in Java
  3. Convert String to Byte Array Java Program
  4. Convert float to String in Java
  5. How to Convert Date to String in Java

You may also like-

  1. Java Program to Find The Longest Palindrome in a Given String
  2. Matrix Multiplication Java Program
  3. How to Run a Shell Script From Java Program
  4. How to Read File From The Last Line in Java
  5. Covariant Return Type in Java
  6. Wildcard in Java Generics
  7. Lambda Expressions in Java 8
  8. Java Stream API Tutorial