Java Enum Keyword

Java Enum Keyword


Enum Keyword In Java
An enumeration is created using the enum keyword. For example, here is a simple enumeration that lists various forms of transportation.
The values( ) method produces an array of the enum constants in the order in which they were declared, so you can use the resulting array in (for example) a for-each loop. 
An object of an enumeration type can hold only the values that are defined by the list.
The main difference between class and enum is enum can not be extended by any class, whereas a class can be extended by other classes, and the main similarity of the two is they both have methods, attributes, and emun can not be used as an object.
Now we will see an example - 
Example - 
// This class is automatically inherited //from java.lang.Enum, which provides //certain capabilities that you can see in //this example-
//: enumerated/EnumClass.java
// Capabilities of the Enum class  
enum Shrubbery { GROUND, CRAWLING, HANGING }
public class EnumClass {
public static void main(String[] args) {
for(Shrubbery s : Shrubbery.values()) {
print(s + " ordinal: " + s.ordinal());
printnb(s.compareTo(Shrubbery.CRAWLING) + " ");
printnb(s.equals(Shrubbery.CRAWLING) + " ");
print(s == Shrubbery.CRAWLING);
print(s.getDeclaringClass());
print(s.name());
print("----------------------");
}
// Produce an enum value from a string name:
for(String s : "HANGING CRAWLING GROUND".split(" ")) {
Shrubbery shrub = Enum.valueOf(Shrubbery.class, s);
print(shrub);
}
}
}
Output -
GROUND ordinal: 0
-1 false false
class Shrubbery

GROUND
----------------------
CRAWLING ordinal: 1
0 true true
class Shrubbery
CRAWLING
----------------------
HANGING ordinal: 2
1 false false
class Shrubbery
HANGING
----------------------
HANGING
CRAWLING
GROUND