Q:

Java program to demonstrate an enum in switch case

belongs to collection: Java Enums Programs

0

Java program to demonstrate an enum in switch case

All Answers

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

In this program, we will create a vehicle enumeration using "enum" inside the class Main. Then we will use an enum constant with a switch case inside the main() method and print the appropriate message.

Program/Source Code:

The source code to demonstrate an enum in the switch case is given below. The given program is compiled and executed successfully.

// Java program to demonstrate an enum 
// in switch case

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

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

    switch (Vehicle.valueOf(str)) {
    case BIKE:
      System.out.println("BIKE is for 2 persons.");
      break;

    case CAR:
      System.out.println("CAR is for 5 persons.");
      break;

    case BUS:
      System.out.println("BUS is for 50 persons.");
      break;

    default:
      System.out.println("Unknown Vehicle.");
      break;
    }
  }
}

Output:

BUS is for 50 persons.

 

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

total answers (1)

Java program to create the main() method inside th... >>
<< Java program to convert the string into an enum co...