Implement Switch on Enum in Java

Java 8Object Oriented ProgrammingProgramming

Enum in Java contains a fixed set of constants. They can have fields, constructors and method. It enhances type safety in Java.

The following is an example wherein we are implementing Switch statement on Enumeration in Java −

Example

 Live Demo

public class Demo {
   public static void main(String[] args) {
      Laptop l = Laptop.Inspiron;
      switch(l){
         case Inspiron:
         System.out.println("Laptop for home and office use!");
            break;
         case XPS:
          System.out.println("Laptop for the ultimate experience!");
            break;
         case Alienware:
          System.out.println("Laptop for high-performance gaming");
            break;
      }
   }
}
enum Laptop {
      Inspiron, XPS, Alienware;
}

Output

Laptop for home and office use!
raja
Published on 20-Dec-2018 05:33:24
Advertisements