Popular Posts

Friday, October 4, 2013

Working with Enums in Java

Definition:
Enums are special kind of datatype which we can use in application as constants. 

Where to Use:
 In java application  we have requirements where we need to keep some values that should be constant throughout the application. There we use enums to keep thos values in meaningful way.Why Enums instead of constants:In java Enums are objects. They can have variables, methods etc. like any other objects. But constants are just like some primitive values. 


package com.technobash.enums;

public enum Months {

 JANUARY(1), 
 FEBRUARY(2),
 MARCH(3),
 APRIL(4),
 MAY(5),
 JUNE(6),
 JULY(7),
 AUGUST(8),
 SEPTEMBER(9),
 OCTOBER(10),
 NOVEMBER(11),
 DECEMBER(12);

 // This is a constructor where we pass the integer value to initialize enums
 Months(int x) {
  this.x = x;
 }

 int x;

 public int getValue() {
  return this.x;
 }
}

Here are some useful links about enums:
Enum Tricks
Enum Examples
Enums Documentation





No comments:

Post a Comment