Quick Reach
Java Enum Type
There are situations in programming where you require variable values to be among the pre-defined constants. For example month names (Jan, Feb, Mar), day names (Sat, Sun, Mon), compass directions (North, East, West, South), marital status (married, single, widowed etc.) and so on. There are other ways to restrict it, Enum is one of the better solution to do it.
A few important points about enum:
- An enum is a special data type
- enum enables for a variable to allow using predefined constants
- That means any value assigned to variable must be equal to one of predefined constant in enumeration
- Enums are type-safety. You can ensure to limit for particular set of values
- Enums can be used with <switch> decision making statements like primitive data types, which is quite useful
- Names of enumeration data type field are in uppercase letters, as such these are constants
- Enum are like class or interface in Java so it can include methods or other fields as well.
- The constants in enum are static and final implicitly i.e. once created it cannot be changed.
- Enum was introduced in JDK 1.5
How to declare an enum
In java an enumeration is declared by using enum keyword as below:
public enum Month {JAN, FEB, MAR, APR}
Example of using enum with month name example
The example below declare a month enum.
First declaring enum Month
1
2
3
4
5
|
public enum Month {JAN, FEB, MAR, APR,
MAY, JUN , JUL, AUG, SEP, OCT, NOV, DEC
}
|
See graphic of above example
Code to work with enum
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
|
public class enum_example {
Month mon;
public enum_example(Month mon) {
this.mon = mon;
}
public void displayenum() {
switch (mon) {
case JAN:
System.out.println("This is January.");
break;
case FEB:
System.out.println("This is February.");
break;
case APR:
System.out.println("This is April");
break;
case MAY:
System.out.println("This is May");
break;
case JUN:
System.out.println("This is June");
break;
case JUL:
System.out.println("This is July");
break;
default:
System.out.println("Other.");
break;
}
}
public static void main(String[] args) {
enum_example firstmon = new enum_example(Month.JAN);
firstmon.displayenum();
enum_example secondmon = new enum_example(Month.FEB);
secondmon.displayenum();
enum_example fourthmon = new enum_example(Month.APR);
fourthmon.displayenum();
enum_example fifthmon = new enum_example(Month.MAY);
fifthmon.displayenum();
enum_example sixmon = new enum_example(Month.JUN);
sixmon.displayenum();
enum_example seventhmon = new enum_example(Month.JUL);
seventhmon.displayenum();
}
}
|
See graphic of above example
The output will be:
This is January.
This is February.
This is April
This is May
This is June
This is July
Also see
Leave A Comment?