Tuesday, 28 March 2017

Converting String to enum type - Java Program

There may be a scenario where a string is passed in your code and you have to convert it into the enum type. 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 the string passed 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.

Example code

enum Day {
public class EnumDemo {

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



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 - Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!

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

You may also like -

>>>Go to Java Programs page

No comments:

Post a Comment