Enum from string Java
In this post, you will learn how to convert enum from string using the Java programming language.
The Enum in Java is a data type which contains a fixed set of constants. The enum keyword is used to create an enum in Java and separate the constants with a comma. This keyword has been introduced since Java 5.
Using the predefined valueOf() method, we can create an enum from a string.
Enum valueOf() method
The valueOf() method returns the value of given constant enum. We can use this method to convert enum from string. The valueOf() method of the Enum class in java accepts a string value and returns an enum constant of the specified type. String name should match with the text used to declare Enum in the Java file. The following example demonstrates this-
public class EnumProgram {
private enum DAY {
SUNDAY {
@Override
public String toString() {
return "Sundays are for rest.";
}
},
MONDAY {
@Override
public String toString() {
return "Mondays are the start.";
}
},
FRIDAY{
@Override
public String toString() {
return "Fridays are for fun.";
}
}
}
public static void main(String[] args) {
// Converting String to Enum in Java
DAY sun = DAY.valueOf("SUNDAY");
System.out.println(sun);
DAY mon = DAY.valueOf("MONDAY");
System.out.println(mon);
DAY fri = DAY.valueOf("FRIDAY");
System.out.println(fri);
}
}
Output of the above code:
Sundays are for rest.
Mondays are the start.
Fridays are for fun.
Related Articles
Java enumSort array in ascending order Java
String reverse in Java
Count vowels in a string Java
Java compare two strings
Java string split multiple delimiters
Char array to string Java
Java find largest of three numbers
Vowel and Consonant program in Java
Star pattern programs in Java
Number pattern programs in Java
Java program to find area of rectangle
Matrix multiplication in Java
Electricity bill program in Java
Java program to find area of triangle
Area of circle program in Java
Remove duplicate elements from array in Java
Capitalize first letter of each word Java
Convert binary to decimal in Java
Convert decimal to binary in Java
Convert decimal to octal in Java
Convert decimal to hexadecimal in Java
Simple interest program in Java