Preparing for Java Interview?

My books Grokking the Java Interview and Grokking the Spring Boot Interview can help

Download PDF

How to convert String to Enum in Java? ValueOf Example

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 the 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 the 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, The string passed to the valueOf method of Java enum must be the same as the String returned by name() method like 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, it's the third tutorial on Enum in Java after the previous post on Java Enum Swith Example  and Java Enum toString example. If you have not read those tutorials you may find them useful. 


valueOf Java Enum Example

Here is a complete code example of the 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.



If you want to learn more about Java programming fundamentals like enum, you can also check out these free Java Programming courses to start with. 

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

public class EnumValueOfExample {

    public static void main(String args[]) {
                 
      //valueOf method returns Enum instance with
      //name matching to String passed to valueOf

      TrafficSignal signal = TrafficSignal.valueOf("RED");
      System.out.println("name : " + signal.name()
                         + " action : " + signal.getAction());
   
      //Another Enum valueOf example
      signal = TrafficSignal.valueOf("GREEN");
      System.out.println("name : " + signal.name()
                        + " action : " + signal.getAction());
   
   
      //valueOf will throw IllegalArgumentException
     // if we pass invalid String

      signal = TrafficSignal.valueOf("Green");
    }
 
}

enum TrafficSignal{
    RED("stop"), GREEN("start"), ORANGE("slow down");
 
    private String action;
 
    public String getAction(){
        return this.action;
    }
    private TrafficSignal(String action){
        this.action = action;
    }
}

Output:
name : RED action : stop
name : GREEN action : start
Exception in thread "main" java.lang.IllegalArgumentException: No enum const class test.TrafficSignal.Green
        at java.lang.Enum.valueOf(Enum.java:196)
        at test.TrafficSignal.valueOf(
EnumValueOfExample.java:34)
        at test.CollectionTest.main(EnumValueOfExample.java:29)
Java Result: 1


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 that is by default available to all enum constants and can be used to get Enum constants from String.


Other Java 5 tutorials you may like

2 comments:

  1. Today, I got this error and spent nearly 30 minutes fixing it because I was puzzled. I can see the constant it there with same case, there was no whitespace or no issue with lower or upper case but I was still getting the same error

    Exception in thread "main" java.lang.IllegalArgumentException: No enum constant "P"
    at java.lang.Enum.valueOf(Enum.java:238)

    andmy Enum class has this

    enum Status{
    P("present"), A("absent")

    private Status(String code){
    ////
    }
    }

    Later I found that it was because of double quotes", I was passing "P" instead of just P on command promt. So be careful, you can get this error using double quotes and because its string its very confusing to solve but finally I solved. Thx

    ReplyDelete

Feel free to comment, ask questions if you have any doubt.