almost 11 years ago
An enum type in Java is a special data type that is defined whenever you need to define a variable with a set of predefined values such as Days of the Week, Months of the Year, items in a menu, etc.
KEY POINTS ABOUT ENUM
EXAMPLE
Let us take a simple example to demonstrate the functionality of enum.
- public enum Month {
- JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE,
- JULY, AUGUST, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER
- }
- Please refer to the code below to see how the enum type Month is used:
- public class EnumExample {
- Month month;
- public EnumExample( Month month) {
- this.month = month;
- }
- public void festivalsRoundTheYear() {
- switch (month) {
- case JANUARY:
- System.out.println("Happy New Year!");
- break;
- case MARCH:
- System.out.println("Happy Holi!");
- break;
- case NOVEMBER:
- System.out.println("Happy Diwali!");
- break;
- case DECEMBER:
- System.out.println("Merry Christmas!");
- break;
- default:
- System.out.println("No festivities.");
- break;
- }
- }
- public static void main(String[] args) {
- EnumExample janMonth = new EnumExample(Month.JANUARY);
- janMonth.festivalsRoundTheYear();
- EnumExample marchMonth = new EnumExample(Month.MARCH);
- marchMonth.festivalsRoundTheYear();
- EnumExample novMonth = new EnumExample(Month.NOVEMBER);
- novMonth.festivalsRoundTheYear();
- EnumExample decMonth = new EnumExample(Month.DECEMBER);
- decMonth.festivalsRoundTheYear();
- EnumExample juneMonth = new EnumExample(Month.JUNE);
- juneMonth.festivalsRoundTheYear();
- }
- }
public enum Month { JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE, JULY, AUGUST, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER } Please refer to the code below to see how the enum type Month is used: public class EnumExample { Month month; public EnumExample( Month month) { this.month = month; } public void festivalsRoundTheYear() { switch (month) { case JANUARY: System.out.println("Happy New Year!"); break; case MARCH: System.out.println("Happy Holi!"); break; case NOVEMBER: System.out.println("Happy Diwali!"); break; case DECEMBER: System.out.println("Merry Christmas!"); break; default: System.out.println("No festivities."); break; } } public static void main(String[] args) { EnumExample janMonth = new EnumExample(Month.JANUARY); janMonth.festivalsRoundTheYear(); EnumExample marchMonth = new EnumExample(Month.MARCH); marchMonth.festivalsRoundTheYear(); EnumExample novMonth = new EnumExample(Month.NOVEMBER); novMonth.festivalsRoundTheYear(); EnumExample decMonth = new EnumExample(Month.DECEMBER); decMonth.festivalsRoundTheYear(); EnumExample juneMonth = new EnumExample(Month.JUNE); juneMonth.festivalsRoundTheYear(); } }
The output is:
Happy New Year!
Happy Holi!
Happy Diwali!
Merry Christmas!
No festivities.
0 Comment(s)