How to iterate the values of an enum using a 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

Live Demo

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

Updated on: 08-Feb-2021

288 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements