How to convert a String to an enum in Java?

Java 8Object Oriented ProgrammingProgramming

The valueOf() method of the Enum class in java accepts a String value and returns an enum constant of the specified type.

Example

Let us create an enum with name Vehicles with 5 constants representing models of 5 different scoters with their prices as values, as shown below −

enum Vehicles {
   //Constants with values
   ACTIVA125(80000), ACTIVA5G(70000), ACCESS125(75000), VESPA(90000), TVSJUPITER(75000); //Instance variable
   private int price;
   //Constructor to initialize the instance variable
   Vehicles(int price) {
      this.price = price;
   }
   //Static method to display the price
   public int getPrice(){
      return this.price;
   }
}

The following Java program, accepts a String value from the user, converts it into an enum constant of the type Vehicles using the valueOf() method and, displays the value (price) of the selected constant.

public class EnumerationExample {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Available scoters: [activa125, activa5g, access125, vespa, tvsjupiter]");
      System.out.println("Enter the name of required scoter: ");
      String name = sc.next();
      Vehicles v = Vehicles.valueOf(name.toUpperCase());
      System.out.println("Price: "+v.getPrice());
   }
}

Output

Available scoters: [activa125, activa5g, access125, vespa, tvsjupiter]
Enter the name of required scoter:
activa125
Price: 80000
raja
Published on 05-Jul-2019 13:44:39
Advertisements