Sunday, January 14, 2024

String to Enum in Java - Example

Creating Enum from String
You can create Enum from String by using Enum.valueOf() method. valueOf() is a static method that is added on every Enum class during compile-time and it's implicitly available to all Enum along with values(), name(), and cardinal() methods. In order to create Enum from String, String must be the same as declared Enum otherwise, the code will throw "java.lang.IllegalArgumentException: No enum const class". the same technique can be used to convert String into Enum instance as well. 

This is the second part of the Enum conversion tutorial, in the first part, we have seen how to convert Enum to String in Java. If you have not read that yet, check it out. 

Also from Java 7 onwards, Java started supporting String constants in switch cases, but you should always prefer Enum over both Integer and String constant because Enum provides type safety. 

The compiler will ensure that incorrect value is not supplied, but in the case of String and Integer, the compiler will check whether a variable is of the correct type, but it won't check values, which is why you should use Enum to define a well-known fixed number of things. 






Enum to String Conversion Example 

Here is a code example of String to Enum conversion in Java. It demonstrates both the technique which we have discussed so far to create Enum from String in Java. You can use the same technique to convert any String to the corresponding Enum as well. 

Always make sure to pass the correct String in order to avoid IllegalArgumentExcpeiton in Java.

There is another method of converting String to Enum as well which compares passed String to all Enum instances declared by iterating over all Enum instances using the values() method and then comparing them using equals(). Though that method works well it requires more code than simple Enum.valueOf().

String to Enum in Java - Example



Problem: We have a declared Enum Currency, which contains Enum instances USD INR EURO, Now We have a String "USD" and we want to convert that String into Enum, it should convert into Currency.USD

Solution: Currency.valueOf("USD") or Enum.valueOf(Currency.class, "USD")

package example;

/**
 * Java program for creating Enum instance from String in Java.
 * This program demonstrates how to use Enum.valueOf() method to convert enum instance
 * into String. beware that String must be the same as declared Enum instances and they are
 * case sensitive as well. "UsD" instead of "USD" will throw IllegalArgumentException
 *
 * @author Javin Paul
 */

public class StringToEnum {
    private enum Currency {USD, AUD, GBP, EURO }  
   
    public static void main(String args[]) {
       
        //Converting String to Enum in Java
        String usd = "USD";
       
        //Enum to String using Enum.valueOf()
        Enum currency = Enum.valueOf(Currency.class, usd);
       
        //Enum to String using Currency.valueOf()
        currency = Currency.valueOf(usd);
       
        System.out.println("String to Enum Example : " + currency);
     
        //This Enum to String conversion will throw Exception
        String INR = "INR";
        //java.lang.IllegalArgumentException: No enum const class
        Currency rupee = Currency.valueOf("INR");
    }
}
Output:
String to Enum Example : USD
Exception in thread "main" java.lang.IllegalArgumentException: No enum const class test.CollectionTest$Currency.INR
        at java.lang.Enum.valueOf(Enum.java:196)
        at test.CollectionTest$Currency.valueOf(CollectionTest.java:16)
        at test.CollectionTest.main(CollectionTest.java:32)
Java Result: 1 


That’s all on How to create Enum from String in Java. This is a very frequent requirement and Java programmers should be familiar with this technique to convert String to Enum easily. In Summary, prefer Enum over String to get compile-time checking and type safety but since String is a global type and you may store your data in the database in the form of String and runtime each of those String converted to Enum.

Related Java Enum Tutorials for further reading :
  1. Java tip to convert  Enum to String in Java (see tip)
  2. How to use the valueOf method of Enum (check here)
  3. String to Enum in Java with Example (check here)
  4. Top 15 Java Enum Interview Questions with Answers (see here)
  5. Difference between RegularEnumSet and JumboEnumSet in Java (read here)
  6. Learn how to use Enum in Java with a Simple Example (check here)
  7. Can we use Enum in Switch Statement in Java (Yes)
  8. How to loop over Enum constants in Java (example)
  9. What Every Java Programmer Should know about Enum (click here)
  10. 10 points about Enum in Java (see here)
  11. Can Enum have Constructor in Java (learn here)
Thanks for reading this article so far. If you find this article useful then please share it on Facebook, Twitter, and LinkedIn. 

6 comments:

  1. I think, it's better to provide factory methods like fromString(String enum) for creating Enum, rather than directly using valueOf(), this will also gives you opportunity to handle issue with String, which can not be converted into Enum.

    ReplyDelete
  2. I have to parse a comma separated String and has to create enum from them e.g. Payment methods : Cheque, Electronic Transfer, Cash, Travelers Cheque etc. Any tips or suggestion how to do this in Java?c

    ReplyDelete
  3. How about valueOf(), in Enum with parametric constructor.
    E.g Protocol(int val), how to get Enum based upon val?

    ReplyDelete
  4. It's important to note that the String argument passed to the valueOf() method is case-sensitive. So passing a value that doesn't match any enum‘s values would lead to an IllegalArgumentException

    ReplyDelete
    Replies
    1. That's great comment about valueOf() method, thx for adding value Abderrahim.

      Delete
  5. Is that screenshot an actual text-editor on mac? If so, which one?

    ReplyDelete

Feel free to comment, ask questions if you have any doubt.