Tutorial for… each loop in Java (in very simple language)
In Java, there is another form of loop (in addition to the standard for loop) for working with arrays and sets.
If you are working with arrays and sets, you can use another for loop structure (advanced for loop form) to duplicate their items.
This type of loop is called for-each because the loop is repeated through each array / set element.
Here is an example of repeating elements of an array using the standard for loop in Java:
- class ForLoop {
- public static void main (String [] args) {
- char [] vowels = {‘a’, ‘e’, ’i’, ‘o’, ‘u’};
- for (int i = 0; i <vowels.length; ++ i) {
- System.out.println (vowels [i]);
- }
- }
- }
You can also write the above code using the for-each loop:
- class AssignmentOperator {
- public static void main (String [] args) {
- char [] vowels = {‘a’, ‘e’, ’i’, ‘o’, ‘u’};
- // foreach loop
- for (char item: vowels) {
- System.out.println (item);
- }
- }
- }
The output of both codes is similar and equal to:
- a
- e
- i
- o
- u
Using the advanced for loop is easier to write and makes the code more readable. Hence it is usually recommended more than the standard form.
For-each ring structure
First let’s look at the for-each loop structure:
for (data_type item: collection) {
…
}
In the above structure,
- collection is a collection or array on which you want to write a circle.
- item is a single element of the collection.
How does the for-each loop work?
Here’s how the for-each loop works.
- Repeat through any element in the given array or collection,
- Stores each item in an item.
- And executes the body of the ring.
Example: for-each loop
The following program calculates the sum of all the elements of an array of integers.
- class EnhancedForLoop {
- public static void main (String [] args) {
- int [] numbers = {3, 4, 5, -5, 0, 12};
- int sum = 0;
- for (int number: numbers) {
- sum + = number;
- }
- System.out.println (“Sum =” + sum);
- }
- }
Output
Sum = 19
In the above program, the execution of the for-each loop is as follows:
You see a repeat of the for-each loop
- All elements of numbers are repeated.
- Each element is stored in the number variable.
- The body of the loop is executed, ie the number is added to the sum.