Wednesday, March 27, 2019

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.

Recommendations for learning (Udemy Courses)

  1. Java Programming Masterclass Course
  2. Java In-Depth: Become a Complete Java Engineer!
  3. Spring Framework Master Class Course
  4. Complete Python Bootcamp Course
  5. Python for Data Science and Machine Learning

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 - Java Program
  2. Converting string to int - Java Program
  3. Converting string to bytearray - Java Program
  4. Converting float to string - Java Program
  5. How to Convert Date to String in Java

You may also like-

  1. How to find the longest palindrome in the 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. Stream API in Java 8