1

Say I have enum values:

public enum Day {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
    THURSDAY, FRIDAY, SATURDAY 
}

Using the enhanced for loop construct, how can I write a code fragment that prints all the days of the week. I'm new to enhanced for loops so i don't know where to start.

Rustam
  • 6,485
  • 1
  • 25
  • 25
Ahmed Abdelazim
  • 133
  • 1
  • 7

3 Answers3

2

enhanced for loop construct

The enhanced for-loop is a popular feature introduced with the Java SE platform in version 5.0. Its simple structure allows one to simplify code by presenting for-loops that visit each element of an array/collection without explicitly expressing how one goes from element to element.

 for(Day days: Day.values()){

      System.out.println(days); // printing days
 }
Rustam
  • 6,485
  • 1
  • 25
  • 25
1

This is how you can use for loop to iterate over all enum constants.

for (Day day : Day.values()) {

    //your code
    //Use variable "day" to access each enum constant in the loop.

}
rajuGT
  • 6,224
  • 2
  • 26
  • 44
1

What you can do is :

for (Day day : Day.values()) {
    System.out.println(day);
}
Roshan Shahukhal
  • 243
  • 4
  • 15