Post Reply 
 
Thread Rating:
  • 1 Votes - 4 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Convert String to Enum Instance in Java
02-13-2011, 11:31 AM
Post: #1
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 com.tutorials4u.java.enum;

public enum Weekdays {
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday
}


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);


Output:
Monday

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);


Output:
Exception in thread "main" java.lang.IllegalArgumentException:
No enum const class net.viralpatel.java.enum.Weekdays.XYZ
at java.lang.Enum.valueOf(Enum.java:192)
Find all posts by this user
Quote this message in a reply
Post Reply 


Forum Jump:



Send your comments, Suggestions or Queries regarding this site at info@tutorials4u.net

Copyright © 2010 Tutorials4u.net All Rights Reserved