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.
- Refer Enum Type in Java to read more about enum in Java.
Example code
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.
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
You may also like -