View RSS Feed

My Java Tips

Using enum types (with example)

Rate this Entry
by , 11-09-2011 at 06:55 PM (1125 Views)
Sometimes it is useful to have a set of values for a variable. Examples can be days of week, planets in the solar system, months of a year, grades of a course, directions etc. This control is useful specially when you are developing a software in a team. So you define boundaries of that type and others have to follow those rules.


In such scenarios, we use enum types. An enum type implicitly extend java.lang.Enum. Its declaration syntax is easy:

Java Code:
public enum Day {
    NORTH, SOUTH, EAST, WEST
}
Now lets take an example:
We have an integer that has value from 1 to 12. It corresponds to month of a year. We have String and want 3 character abbreveation of the month to which that integer points to. We have methods in Java that can do this but, here we will do it ourselves using enum.


Java Code:
public class Month {

	public enum MyMonth {
		XXX,JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC
	}

	public static void main(String[] args) {

		int intMonth = 5;
		MyMonth strMonth= MyMonth.XXX;

		switch(intMonth)
		{
		case 1:
		{
			strMonth = MyMonth.JAN;
			break;
		}
		case 2:
		{
			strMonth = MyMonth.FEB;
			break;
		}
		case 3:
		{
			strMonth = MyMonth.MAR;
			break;
		}
		case 4:
		{
			strMonth = MyMonth.APR;
			break;
		}
		case 5:
		{
			strMonth = MyMonth.MAY;
			break;
		}
		case 6:
		{
			strMonth = MyMonth.JUN;
			break;
		}
		case 7:
		{
			strMonth = MyMonth.JUL;
			break;
		}
		case 8:
		{
			strMonth = MyMonth.AUG;
			break;
		}
		case 9:
		{
			strMonth = MyMonth.SEP;
			break;
		}
		case 10:
		{
			strMonth = MyMonth.OCT;
			break;
		}
		case 11:
		{
			strMonth = MyMonth.NOV;
			break;
		}
		case 12:
		{
			strMonth = MyMonth.DEC;
			break;
		}
                default: strMonth = MyMonth.XXX;

		}

		System.out.println("Month is: " + strMonth);

	}

}
Output:


Month is: MAY

The code is simple. We have an int value in intMonth. We declared an enum type called MyMonth that has all the months in it. Also it has xxx at start which will means no month found. Now we will use a switch statement to assign value to strMonth which is of enum (MyMonth) type. If intMonth has values less than 1 or more than 12, then strMonth get XXX value which means no matching month found.

Submit "Using enum types (with example)" to Facebook Submit "Using enum types (with example)" to Digg Submit "Using enum types (with example)" to del.icio.us Submit "Using enum types (with example)" to StumbleUpon Submit "Using enum types (with example)" to Google

Tags: None Add / Edit Tags
Categories
Java SE

Comments