The enumeration is introduced to Java from the JDK 5 version.
An enumeration in general is a list of named constants. The enumeration is also
supported by C++ programming language where it is only a simple list of named
integer constants. But in Java, an enumeration defines a class type. It can
also have a method, constructor, instance variables and also inherit other
enumerations.
How to create an Enumeration?
The enum keyword is used to create the enumeration.
The general form
of an enumeration is shown below.
enum EnumName
{
identifier1, identifier2,…identifierN
}
|
The identifier1,
identifier2 and so on are called enumeration
constants. Each of these enumeration constants are implicitly declared as public, static and final members of enumerations.
Consider the
below example that creates an enumeration called DogName.
package blog.enumeration;
public enum DogName
{
labradorRetriever, germanShepherd, boxer, goldenRetriever, beagle
}
|
Here, labradorRetriever,
germanShepherd, boxer, goldenRetriever, beagle are of the type DogName.
Consider the below
program example that shows how enumeration is used with regular class.
package blog.enumeration;
public enum Operators
{
add, subtract, multiple, divide
}
|
package blog.enumeration;
public class DemoEnumOperators
{
public static void main(String[] args)
{
int a=10, b=5;
int result=0;
Operators op; // variable of type
enumeration Operators is created.
op=Operators.add;
//displaying enumeration
values
System.out.println("value of variable op is
"+op);
op=Operators.multiple; // op assigned
to multiple identifier of enumeration.
switch(op)
{
case add:
result=a+b;
break;
case subtract:
result=a-b;
break;
case multiple:
result=a*b;
break;
case divide:
result=a/b;
break;
}
System.out.println("result from switch
statement "+result);
}
}
|
Output:
value of variable op is add
result from switch statement 50
|