Java Program to Access Enum Constants Using ‘For Each’ Loop

You are currently viewing Java Program to Access Enum Constants Using ‘For Each’ Loop

Java program to access enum constants using ‘for each’ loop

// 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

Ranjith

Hi, I'm Manoj a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Diksha. Here, I post about programming to help developers.

Leave a Reply