The valueOf()
method of an enum type allows you to get an enum constant that the value corresponds to the specified string. Exception will be thrown when we pass a string that not available in the enum.
package org.kodejava.basic;
public enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}
package org.kodejava.basic;
public class EnumValueOfTest {
public static void main(String[] args) {
// Using valueOf() method we can get an enum constant whose
// value corresponds to the string passed as the parameter.
Day day = Day.valueOf("SATURDAY");
System.out.println("Day = " + day);
day = Day.valueOf("WEDNESDAY");
System.out.println("Day = " + day);
try {
// The following line will produce an exception because the
// enum type does not contain a constant named JANUARY.
day = Day.valueOf("JANUARY");
System.out.println("Day = " + day);
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
}
}
The output of the code snippet above:
Day = SATURDAY
Day = WEDNESDAY
java.lang.IllegalArgumentException: No enum constant org.kodejava.basic.Day.JANUARY
at java.base/java.lang.Enum.valueOf(Enum.java:273)
at org.kodejava.basic.Day.valueOf(Day.java:3)
at org.kodejava.basic.EnumValueOfTest.main(EnumValueOfTest.java:15)
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024