What is Enumeration (JNNC Technologies)


Enumeration is a list of named constants and these Java enumerations define a class type. By making enumerations into classes, the concept of enumeration is greatly expanded in Java. In the simplest form, Java enumerations appear similar to enumerations in other languages, except that the classes play a major role in this concept.
Java Enumeration
Enumeration is used using the keyword enum. For example: here are the lists of various types of programming languages declared using enumeration.
Example:
// an enumeration of varieties of programming languages
enum PLtypes
{
highlevel, machinelevel, assembly, middlelevel
}

Here, the identifiers - high-level, machinelevel etc are called enumeration constants.
Each of them is implicitly declared as public, static final members of PLtypes enumeration. Hence, in the language of Java, these constants are referred to as self-typed, where self refers to enclosing enumeration. Once the enumeration is defined, programmers can create a variable of its type. However, even though enumerations define a class type, programmers do not initiate an enum using new, instead, they can declare and use enumeration variable like that of primitive data types as used before. For example, this declares langas a variable of enum type PLtypes like this:
PLtypes lang;
lang = PLtypes.assembly;
Two enumeration constants can be compared for checking equality by the use of the == relational operator. For example, this compares the value of lang as the value machine-level:
if (lang == PLtypes.machinelevel)
{
// . . . . . .
}
It is to be noted that an enumeration value can also be used to control a switch statement. It is, of course, necessary that all of the case statements must use constants from the same enum as that used by the switch statement. For example, below mentioned switch case statement is a valid statement in Java:
// use enum to control Switch cases
switch (lang)
{
case assembly:
// . . . . . . . .
Case middlelevel:
// . . . . . . . .
//         . . . .
}

Values() and valuesOf() methods

All enumerations automatically contain two predefined methods: values() and valuesOf(). The general forms of these statements are:
public static enum-type[ ] values()
public static enum-types valuesOf (string str)
The values() method returns an array that contains a list of the enumeration constants and the valueOf() method returns the enumeration constant whose values corresponds to the string passed in str.

0 Comments

'; (function() { var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true; dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js'; (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq); })();