How do I use for-each in Java?

Using for-each command to iterate arrays or a list can simplified our code. Below is an example how to do it in Java. The first loop is for iterating array and the second for iterating a list containing a some names.

package org.kodejava.lang;

import java.util.ArrayList;
import java.util.List;

public class ForEachExample {
    public static void main(String[] args) {
        Integer[] numbers = {10, 100, 1000, 10000, 100000, 1000000};

        for (Integer i : numbers) {
            System.out.println("Number: " + i);
        }

        List<String> names = new ArrayList<>();
        names.add("Musk");
        names.add("Nakamoto");
        names.add("Einstein");

        for (String name : names) {
            System.out.println("Name: " + name);
        }
    }
}

The result of the code snippet:

Number: 10
Number: 100
Number: 1000
Number: 10000
Number: 100000
Number: 1000000
Name: Musk
Name: Nakamoto
Name: Einstein
Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.