Pages

Java Enum ValueOf Example - How to use

valueOf Example in Java Enum

valueOf method of Java Enum is used to
retrieve Enum constant declared in Enum Type by passing String in other words valueOf method is
used to convert
String to Enum constants. In this Java Enum valueOf example we
will see how to use valueOf method in Java. valueOf method is
implicitly available to all Java
Enum because every enum in Java implicitly extends java.lang.Enum class. valueOf method of
enum accepts exactly same String which is used to declare Enum constant to
return that Enum constant. valueOf method is case-sensitive
and invalid String will result in IllegalArgumentException. In short
String passed to valueOf method of Java enum must be same
to String returned by name() method e.g. TrafficSigal.RED.name() returns
RED and you should pass RED to valueOf() to get TrafficSignal.RED. This will
be more clear will following Java Enum valueOf example. By the way its third
tutorial on Enum in Java after previous post on Java
Enum Swith Example and Java
Enum toString example. If you have not read those tutorial you may find
useful.

valueOf Java Enum Example

Here is complete code example of valueOf method of
Java Enum. In this enum example we have used a TrafficSignal Enum to
demonstrate how we can retrieve Enum
from String in Java.

/**
*
* Java program to show How to use valueOf method of Enum
* to create enum. This is simple Enum valueOf example which
* teaches how to use valueOf method.
*
* @author
*/publicclass
EnumValueOfExample {

That's all on this Java Enum valueOf example. See 10
Java enum Examples for more examples of enum in Java. In short enum valueOf
is a useful method which is by default available to all enum constants and can
be used to get Enum constants from String.