Version prior to JDK 5 lacked one feature that many programmers felt was needed: enumeration. In its simplest form, an enumeration is a list of named constants.

Although Java offered other features that provide somewhat similar functionality, such as final variables, many programmers still missed the conceptual purity of enumerations- especially because it is supported by most other commonly used languages.

Beginning with JDK 5, enumerations were added to Java language, and they are now available to the Java programmer.

In their simplest form, Java enumerations appear similar to enumerations in other languages.

However, this similarity is only skin deep. In languages, such as C++, enumerations are simply lists of named integer constants.

In java, an enumeration defines a class type. By making enumerations into classes,  the concept of the enumeration is greatly expanded.

For therefore, although enumerations were several years in the making, Java’s rich implementation made them well worth the waitJava enumerations

Enumeration Fundamentals –

An enumeration is created using the enumkeyword.

For example, here is a simple enumeration that lists various apple varities :

// An enumeration of apple varieties.

Enum Apple {

Jonathan, GoldenDel, RedDel, Winesap, Cortland

}

The identifiers Jonathan, GoldenDel, and so on, are called enumeration constants.

Each is implicity declared as a public, static final member of Apple.

Furthermore, their type is the type of the enumeration in which they are declared, which is Apple in this case.

Thus, in the language of Java, these constants are called self-typed, in which “self” refers to the enclosing enumeration.

Once you have defined an enumeration, you can create a variable of that type.

Recommended Post   Java Arrays

However, even though enumerations define a class type, you do not instantiate an enumusing new.

Instead, you declare and use an enumeration variable in much the same way as you do one of the primitive types.

For example, this declares apas a variable of enumeration type Apple : Apple ap ;

Because apis of the type Apple, the only values that it can be assigned (or can contain) are those defined by the enumerations. For example, this assigns apthe value RedDel :

Ap = =Apple.RedDel :

Notice that the symbol RedDel is preceded by Apple.

Two enumeration constants can be compared for equality by using the = = relational operator.

For example, this statement compares the value in apwith the GoldenDelconstant :

If(ap = = Apple.GoldenDel) // . . . .

An enumeration value can also be used to control a switch statement.

Of course, all of the case statements must use constants from the same enumas that used by the switch expression.

For example, this switch is perfectly valid :

// Use an enum to control a switch statement .

switch (ap ) {

case Jonathan :

// . . . .

Case Winesap :

// . . . .

LEAVE A REPLY

Please enter your comment!
Please enter your name here