How to iterate the values of an enum using a for loop in Java?

JavaServer Side ProgrammingProgramming

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
raja
Published on 08-Feb-2021 11:26:53
Advertisements