Java program to access enum constants using 'for each' loop

Java example to access enum constants using 'for each' loop.
Submitted by Nidhi, on April 04, 2022

Problem Solution:

In this program, we will create a class that contains an enum and main() method. Then we will access the enum constants using the values() method and print the enum constants and their index using for each loop.

Program/Source Code:

The source code to access enum constants using "for each" loop is given below. The given program is compiled and executed successfully.

// Java program to access enum constants 
// using "for each" loop

public class Main {
  enum Vehicle {
    BIKE,
    CAR,
    BUS
  }

  public static void main(String[] args) {
    Vehicle arr[] = Vehicle.values();

    for (Vehicle v: arr) {
      System.out.println(v + " at index " + v.ordinal());
    }
  }
}

Output:

BIKE at index 0
CAR at index 1
BUS at index 2

Explanation:

In the above program, we created a class Main that contains the enum constant and main() method. Here, we created an array of objects of the enumeration Vehicle and, initialize it using the values() method. Then we got the index of enum constants using the ordinal() method. After that, we printed the enum constants and their index using "for each" loop.

Java Enums Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.