How to use an enum with switch case in Java?\\n



Enumeration (enum) in Java is a datatype which stores a set of constant values. You can use enumerations to store fixed values such as days in a week, months in a year etc.

enum Days { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY }

You can also define an enumeration with custom values to the constants declared. But you need to have an instance variable, a constructor and getter method to return values.

Enum with switch case

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

enum Scoters { //Constants with values ACTIVA125(80000), ACTIVA5G(70000), ACCESS125(75000), VESPA(90000), TVSJUPITER(75000); //Instance variable private int price; //Constructor to initialize the instance variable Scoters(int price) { this.price = price; } //Static method to display the price public static void getPrice(int model){ Scoters constants[] = Scoters.values(); System.out.println("Price of: "+constants[model]+" is "+constants[model].price); } }

Following Java program retrieves the prices of all the vehicles using switch case.

Example

public class EnumExample {    Scoters sc;    public EnumExample(Scoters sc) {       this.sc = sc;    }    public void displayPrice() {       switch (sc) {          case Activa125:             Scoters.getPrice(0);             break;          case Activa5G:             Scoters.getPrice(1);             break;          case Access125:             Scoters.getPrice(2);             break;          case Vespa:             Scoters.getPrice(3);             break;          case TVSJupiter:             Scoters.getPrice(4);             break;          default:             System.out.println("Model not found");             break;       }    }    public static void main(String args[]) {       EnumExample activa125 = new EnumExample(Scoters.ACTIVA125);       activa125.displayPrice();       EnumExample activa5G = new EnumExample(Scoters.ACTIVA5G);       activa5G.displayPrice();       EnumExample access125 = new EnumExample(Scoters.ACCESS125);       access125.displayPrice();       EnumExample vespa = new EnumExample(Scoters.VESPA);       vespa.displayPrice();       EnumExample tvsJupiter = new EnumExample(Scoters.TVSJUPITER);       tvsJupiter.displayPrice();    } }

Output

Price of: ACTIVA125 is 80000 Price of: ACTIVA5G is 70000 Price of: ACCESS125 is 75000 Price of: VESPA is 90000 Price of: TVSJUPITER is 75000
Updated on: 2019-07-30T22:30:26+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements