ADVERTISEMENT
ADVERTISEMENT

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 »


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.