Exercise:
Write a Java Program to iterate over enum.
1.Iterate using for-each loop
Click Here to View the Solution!
enum Languages {
JAVA, JAVASCRIPT, SWIFT, CPP,HTML
}
public class Main {
public static void main(String[] args) {
System.out.println("Access each enum constant");
// use foreach loop to access each value of enum
for(Languages language: Languages.values()) {
System.out.print(language + ", ");
}
}
}
Click Here to View the Output!
Access each enum constant JAVA, JAVASCRIPT, SWIFT, CPP, HTML,
Click Here to View the Explanation!
- This program deals with the task of looping over an
enum
by utilizing for-each loop
. - For this purpose, we created a simple
enum
first. - This
enum
is namedLanguages
in this case, initialized by usingenum
keyword. - It constitutes five constants
JAVA, JAVASCRIPT, SWIFT, CPP and HTML
. - In the main method a message is displayed indicating that
enum
is being accessed. - After that, in for-each loop the program iterates over
Languages
and displays each value using thevalues()
method. - This method is responsible for transforming
enum
constants into an array, in order to be displayed as elements of an array.
2.Iterate using EnumSet Class
Click Here to View the Solution!
import java.util.EnumSet;
// create an enum
enum Languages {
JAVA, JAVASCRIPT, SWIFT, CPP,HTML
}
public class Main {
public static void main(String[] args) {
// convert the enum Size into the enumset
EnumSet<Languages> enumSet = EnumSet.allOf(Languages.class);
System.out.println("Elements of EnumSet: ");
// loop through the EnumSet class
for (Languages constant : enumSet) {
System.out.print(constant + ", ");
}
}
}
Click Here to View the Output!
Elements of EnumSet: JAVA, JAVASCRIPT, SWIFT, CPP, HTML,
Click Here to View the Explanation!
- This program deals with the task of looping over an
enum
by utilizingEnumSet
class. - For this purpose, we created a simple enum first.
- This enum is named
Languages
in this case, initialized by usingenum
keyword. - It constitutes five constants
JAVA, JAVASCRIPT, SWIFT, CPP and HTML
. - In the main method we have used
EnumSet
class to create a set from theLanguages enum
. - For this we specify the type of
enum Languages
, and fetch all the elements using theallOf()
method provided byEnumSet
class. - After that, in for-each loop the program iterates over
Languages
and displays each value using theenumSet
.