Enum in java

March 04, 2011 by Sandeep Bhardwaj | Tags:


Enum: Get value using enum

enum Day {  
    SUNDAY(1), MONDAY(2), TUESDAY(3), WEDNESDAY(4), THURSDAY(5), FRIDAY(6), SATURDAY(7);  
    private final int dayCode;  
    private Day(int dayCode)  
    {  
     this.dayCode = dayCode;  
    }  
    public int getCode() { return dayCode; }  
}  

public class EnumValueOfDay {  
    public static void main(String[] args) {  

        Day day =    Day.SUNDAY;  
        System.out.println("Day = " + day.getCode());            
    }  
}  

also you can use enum in this way to get the value of enum . Here is one more example to print the names by using toString method.

enum Name {  
 S("Sandeep"),   
 A("Aditya") ,   
 R("Rambrij"),  
 M("Meenakshi");  

 private final String name;  

 private Name(String name) {  
  this.name = name;  
 }  

 public String toString() {  
  return name;  
 }  
}  

public class NameDisplay {  
 public static void main(String[] args) {  

  Name name = Name.A;  
  System.out.println("Name = " + name);  
 }  
}