Monday, 30 January 2017

ENUM IN JAVA

Enum is a type of class which is final. It is created by using the keyword “enum”. It is used for defining set of named constants those representing a menu kind of items. For example – Hotel menu, Bar menu etc. Before java 5 these items were created using class. Class has a problem in accessing these menu items, that it cannot return or print item name as it is declared, instead it returns or prints its value.

Example with class –
class Months{
          static final int jan=1;
          static final int feb=2;
}
public class Year {
          public static void main(String[] args)
          {
                   System.out.println(Months.jan);
                   System.out.println(Months.feb);
          }
}

Output –
1
2

Example with enum –
public enum Months {
          jan,feb;
}
class Year{
          public static void main(String[] args)
          {
                   System.out.println(Months.jan);
                   System.out.println(Months.feb);
          }
}

Output –
jan
feb

Example –
public class Test2 {
          public enum Season { WINTER, SPRING, SUMMER, FALL }
          public static void main(String[] args) {
                   for (Season s : Season.values()) 
                             System.out.println(s); 
          }
}

Output –
WINTER
SPRING
SUMMER
FALL

Note - The java compiler internally adds the values() method when it creates an enum. The values() method returns an array containing all the values of the enum.

Example –
public class Test2 {
          public enum Season { WINTER, SPRING, SUMMER, FALL }
          public static void main(String[] args) {
                   Season s = Season.WINTER;
                   System.out.println(s);
          }
}

Output –
WINTER

Example –
public class Test2 {
          enum Season{  
                   WINTER(5), SPRING(10), SUMMER(15), FALL(20);                     
                   private int value
                   private Season(int value){ 
                   this.value=value;
                   }
          }
          public static void main(String[] args) {
                   for (Season s : Season.values()) 
                             System.out.println(s+" "+s.value);
          }
}

Output –
WINTER 5
SPRING 10
SUMMER 15
FALL 20 

No comments:

Post a Comment