Java for each Loop
In Java, the enhanced for loop, also known as the "for-each" loop, is a convenient way to iterate over collections and arrays. It provides a simpler and more concise way to loop through the elements of a collection or array without using the traditional for
loop with an index variable.
Here is the basic syntax of the for-each
loop in Java:
for (element_type element : collection) { // code to execute for each element }
In this syntax, element_type
is the type of the elements in the collection, and element
is a variable that represents each element in the collection. collection
is the collection or array that you want to loop through.
Here is an example that uses the for-each
loop to iterate over an array of strings:
String[] names = {"Alice", "Bob", "Charlie"}; for (String name : names) { System.out.println(name); }
In this example, the for-each
loop iterates over the names
array, and assigns each element of the array to the name
variable in turn. The loop prints each element of the names
array for each iteration, resulting in the names "Alice", "Bob", and "Charlie" being printed to the console.
You can also use the for-each
loop to iterate over collections such as ArrayList
, LinkedList
, HashSet
, and HashMap
. Here is an example that uses the for-each
loop to iterate over an ArrayList
of integers:
ArrayList<Integer> numbers = new ArrayList<>(); numbers.add(1); numbers.add(2); numbers.add(3); for (int number : numbers) { System.out.println(number); }
In this example, the for-each
loop iterates over the numbers
ArrayList
, and assigns each element of the list to the number
variable in turn. The loop prints each element of the numbers
ArrayList
for each iteration, resulting in the numbers 1, 2, and 3 being printed to the console.