Convert String to Enum Java

Convert String to Enum Java | The string is the collection of a sequence of characters and the enum is the collection of constant values. Enum is expanded as enumeration, it is a special class that has constant values & enum keyword is used to define the class. Here we will see how to convert string to enum In Java. We will see the java convert string to enumeration through multiple examples.

Java Convert String to Enumeration

Here we have created an enum inside the main class, the enum is defined for colors then in the main method we take some color string and check if it is available in the colors or not and then return the enum.

public class Main {

   enum Color {
      RED, PINK, YELLOW;
   }

   public static void main(String[] myArgs) {
      Color color = Color.valueOf("RED");
      System.out.println(color);
      System.out.println(color == Color.RED);
   }
}

Output:-

RED
true

Java Convert From String To Enum

In this code we have taken the example of sizes we have defined four different sizes SMALLER, MEDIUM, LARGER, EXTRALARGER. In the main method access these sizes and convert them to enum. 

enum Sizes {
   SMALLER, MEDIUM, LARGER, EXTRALARGER
}

public class Main {
   public static void main(String[] args) {
      System.out.println("The string value of SMALL is: " 
                         + Sizes.SMALLER.toString());
      System.out.println("The string value of MEDIUM is: " 
                         + Sizes.MEDIUM.name());
   }
}

Output:-

The string value of SMALL is: SMALLER
The string value of MEDIUM is: MEDIUM

Program to Convert String to Enum Java

To convert string to enum in Java we have defined enum of sizes there are two sizes small and smaller and use it in the main method is print enum.

enum Size {
   SMALL {
      public String toString() {
         return "The size is small.";
      }
   },

   SMALLER {
      public String toString() {
         return "The size is SMALLER.";
      }
   };
}

public class Main {
   public static void main(String[] args) {
      System.out.println(Size.SMALLER.toString());
   }
}

Output:-

The size is SMALLER.

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published.