tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 Java > Collection > Enum > Enum Switch Case

Enum Switch Case 

The following example shows how to use enum in switch case. All enum types implicitly implements java.io.Serializable and java.lang.Comparable. Note that in switch case we have given unqualified enum constant name without enum type prefix. Enum provides the following APIs,

public static <E extends Enum<E>> E[] values();
 - Returns all enum constants of this element type. 


File Name  :  
com/bethecoder/tutorials/utils/enums/EnumSwitchTests.java 
Author  :  Sudhakar KV
Email  :  [email protected]
   
package com.bethecoder.tutorials.utils.enums;

public class EnumSwitchTests {

  /**
   @param args
   */
  public static void main(String[] args) {

    /**
     * Get all enum constants of this type as array
     */
    Fruit [] fruits = Fruit.values();
    
    for (int i = ; i < fruits.length ; i ++) {
      
      switch(fruits[i]) {
        case MANGO:
        case APPLE:
          System.out.println(fruits[i" is a tasty fruit");
          break;
          
        case ORANGE:
        case CHERRY:
          System.out.println(fruits[i" is a nice fruit");
          break;
          
        default:
          System.out.println(fruits[i" is a normal fruit");
      }
    }
    
  }
  
}
   


File Name  :  
com/bethecoder/tutorials/utils/enums/Fruit.java 
   
package com.bethecoder.tutorials.utils.enums;

public enum Fruit {
  APPLE,
  ORANGE,
  BANANA,
  CHERRY,
  MANGO
}
   

It gives the following output,
APPLE is a tasty fruit
ORANGE is a nice fruit
BANANA is a normal fruit
CHERRY is a nice fruit
MANGO is a tasty fruit



 
  


  
bl  br