जावा में एन्यूमरेशन नामित स्थिरांक के एक समूह का प्रतिनिधित्व करता है, आप निम्नलिखित सिंटैक्स का उपयोग करके एक एन्यूमरेशन बना सकते हैं -
enum Days {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
} आप मान () विधि का उपयोग करके एक एनम की सामग्री को पुनः प्राप्त कर सकते हैं। यह विधि सभी मानों वाली एक सरणी लौटाती है। एक बार जब आप सरणी प्राप्त कर लेते हैं तो आप लूप के लिए इसे पुनरावृति कर सकते हैं।
उदाहरण
public class IterateEnum{
public static void main(String args[]) {
Days days[] = Days.values();
System.out.println("Contents of the enum are: ");
//Iterating enum using the for loop
for(Days day: days) {
System.out.println(day);
}
}
} आउटपुट
Contents of the enum are: SUNDAY MONDAY TUESDAY WEDNESDAY THURSDAY FRIDAY SATURDAY
उदाहरण
enum Vehicles {
//Declaring the constants of the enum
ACTIVA125, ACTIVA5G, ACCESS125, VESPA, TVSJUPITER;
int i; //Instance variable
Vehicles() { //constructor
}
public void enumMethod() { //method
System.out.println("Current value: "+Vehicles.this);
}
}
public class Sam{
public static void main(String args[]) {
Vehicles vehicles[] = Vehicles.values();
for(Vehicles veh: vehicles) {
System.out.println(veh);
}
vehicles[3].enumMethod();
}
} आउटपुट
ACTIVA125 ACTIVA5G ACCESS125 VESPA TVSJUPITER Current value: VESPA