
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Iterate Enum Values Using For Loop in Java
Enumerations in Java represents a group of named constants, you can create an enumeration using the following syntax −
enum Days { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY }
You can retrieve the contents of an enum using the values() method. This method returns an array containing all the values. Once you obtain the array you can iterate it using the for loop.
Example
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); } } }
Output
Contents of the enum are: SUNDAY MONDAY TUESDAY WEDNESDAY THURSDAY FRIDAY SATURDAY
Example
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(); } }
Output
ACTIVA125 ACTIVA5G ACCESS125 VESPA TVSJUPITER Current value: VESPA
Advertisements