Using enum types (with example)
17 November 2007Sometimes 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:
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 abreaction 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.
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.
Related Posts:
- Annotating an annotation- I
- Annotating an annotation- II
- Enumeration/Enum Spanning
- Java built-in data types (performance issues)
- Custom annotations - Adding a member - I
- Struts 1 vs Struts 2 (III)
- Annotating an annotation- III
- Custom annotations - default values - I
- Autoboxing And Unboxing in Java 5
- Searching methods with some return type
Top Of Page | Trackback
If you found this page useful, consider linking to it. Simply copy and paste the code below into your web site.
It will look like this: Using enum types (with example)