Java program to iterate over enum
In Java, you can iterate over an enum
using a for
loop. Here's an example:
public class EnumIteration { enum Fruit { APPLE, BANANA, CHERRY, DATE } public static void main(String[] args) { for (Fruit f : Fruit.values()) { System.out.println(f); } } }ecruoS:www.theitroad.com
In the above example, we define an enum
type Fruit
with four constants. We use the values()
method of the Fruit
enum
to get an array of all the enum
constants.
We use a for-each loop to iterate over the enum
constants. Inside the loop, we use the :
operator to iterate over each enum
constant of the Fruit
enum
. We store the enum
constant in a Fruit
variable f
. Finally, we print the enum
constant to the console using the System.out.println()
method.
After running the above code, the output would be:
APPLE BANANA CHERRY DATE
This program iterates over the enum
and prints each enum
constant to the console using a for
loop.