What is enum and When to use

enum

  • Enum is a predefined list of values which do not represent some kind of numeric or textual data.
  • You can use enums when a variable can only take one out of a small set of possible values. Examples will be like type days(“Mon”,”Tue”,”Wed”,”Thu”,”Fri”,”Sat”,”Sun”).

enum days{

MON, TUE, WED, THU, FRI, SAT, SUN

}

Example

public class EnumExample {
   public enum Day {
      MON, TUE, WED, THU, FRI, SAT, SUN
   }
   Day dName;

   public EnumExample(Day dName) {
      this.dName = dName;
   }

   public void dayFeelings () {
      switch (dName) {
         case MON:
            System.out.println("Week starts :(");
            break;

         case SAT: case SUN:
            System.out.println("Weekend Yay!");
            break;

         default:
            System.out.println("Waiting for weekend…");
            break;
      }
   }

   public static void main(String[] args) {
      EnumExample mon = new EnumExample(Day.MON);
      mon.dayFeelings();
      EnumExample tue = new EnumExample(Day.TUE);
      tue.dayFeelings();
      EnumExample sat = new EnumExample(Day.SAT);
      sat.dayFeelings();
      EnumExample thu = new EnumExample(Day.THU);
      thu.dayFeelings();
   }
}

Output….

Week starts 🙁
Waiting for weekend…
Weekend Yay!
Waiting for weekend…

 

Important points

You can not assign any value other than specified in Enum Constants.

enum Color{
   YELLOW, GREEN, RED
}

Color c = Color.RED;
c = 1;           // Compilation Error

MyEnum.values() returns an array of MyEnum’s values

public class EnumExample{
   public enum Color{
      YELLOW(10), GREEN(20), RED(30);
      private int value;
      private Color(int value){
         this.value=value; 
      }
   }

   public static void main(String[] args){
      for(Color c: Color.values()){
         System.out.println("Color value: "+c.value+" Color name: "+c);
      }
   }

output…

Color value: 10 Color name: YELLOW
Color value: 20 Color name: GREEN
Color value: 30 Color name: RED

 

Leave A Comment

Your email address will not be published. Required fields are marked *