Convert String to Enum Instance in Java

Recently while working in one of the requirement, I had to convert String values to Enum. I didn’t realize there is a simplest way of doing this. Here is the solution. Whenever an ENUM is complied in Java, two static methods are added by compiler called valueOf() and values(). We can use valueOf() method to convert any String value to ENUM. For example lets say we have an ENUM called Weekdays.
package; public enum Weekdays { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday }
Code language: Java (java)
Now we want to get an instance of Weekdays enum from string values lets say “Monday”, “Tuesday” etc. We can get this as follow:
Weekdays weekday = Weekdays.valueOf("Monday"); System.out.println(weekday);
Code language: Java (java)
One thing we need to take care here is if we pass an invalid string to valueOf() method like “XYZ”, the method will give a runtime exception.
Weekdays weekday = Weekdays.valueOf("XYZ"); System.out.println(weekday);
Code language: Java (java)
Exception in thread "main" java.lang.IllegalArgumentException: No enum const class at java.lang.Enum.valueOf(
Code language: Java (java)
Happy converting :)
Get our Articles via Email. Enter your email address.

You may also like...


  1. It is a bad practice to do this. Basically, your client code will have a fragile dependency on the name of an enum encoded as a string. it’s a variation of the “stringly typed system” smell.

    Read more here:

  2. Sridhar Davuluri says:

    Tq.. it was helpful :)

Leave a Reply

Your email address will not be published. Required fields are marked *