Q:

Java program to convert the string into an enum constant

belongs to collection: Java Enums Programs

0

Java program to convert the string into an enum constant

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program/Source Code:

The source code to convert the string into an enum constant is given below. The given program is compiled and executed successfully.

// Java program to convert the string 
// into an enum constant

public class Main {
  enum Vehicle {
    BIKE,
    CAR,
    BUS
  }

  public static void main(String[] args) {
    String str = "BUS";

    Vehicle v = Vehicle.valueOf(str);

    System.out.println(str);
  }
}

Output:

BUS

Explanation:

In the above program, we created an enumeration Vehicle inside class Main. The enum Vehicle contains 3 constants BIKE, CAR, BUS. The Main class also contains a static method main(). The main() method is the entry point for the program, here we created a string variable initialized with "BUS". Then we converted the string into an enum constant using the valueOf() method and printed the result.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java program to demonstrate an enum in switch case... >>
<< Java program to create an enum inside the class...