Skip to main content

Java: for-each Loop

Introduced in java5 for-each or some call it advanced for loop is another looping traversing method used in the same way such as for loop, while loop, do-while loop.

  • Mainly used for looping through arrays or a collection class.
  • It looks normally like a for a loop but here it only has the return type of the array, our variable followed by a colon, and the array that needs to be traversed.
  • We can access the looped arrays inside the loop body via the custom variable we created and not via index like for loop.

Syntax

for(Returntype variableName : arrayName)
{
    //body
}

Example

public class Test
{
    public static void main(String[] args)
    {
        String[] ps4Exclusives = {"Uncharted", "God Of War", "Spiderman", "Death Stranding"};
        
        for(String finalList : ps4Exclusives)
        {
            System.out.println(finalList);
        }
    }
}

Output

Uncharted
God Of War
Spiderman
Death Stranding

Looks simple right?

As you can see we have traversed through an array of strings and got the list of the traversed and printed it. The return was taken and our variable finalList followed by a colon and the variable name of the string array ps4Exclusives.

Example: Traverse ArrayList

Let us see how we can traverse through ArrayList using this for each.

import java.util.ArrayList;

public class Test
{
    public static void main(String[] args)
    {
        ArrayList<Integer> number = new ArrayList<Integer>();

        number.add(40);
        number.add(60);
        number.add(80);

        for(Integer arrayListNumbers : number)
        {
            System.out.println(arrayListNumbers);
        }
    }
}

Output

40
60
80

Looks the same as we did for the string array. Similarly, we can follow this same method for char array, int array, etc.

Tags
Submitted by arilio666 on October 26, 2021

Ashwin is working with iVagus as a Technical Lead. He has experience in various technologies like Cypress, JavaScript, TypeScript, Rest Assured, Selenium, Cucumber, and Java.

About

At ProgramsBuzz, you can learn, share and grow with millions of techie around the world from different domain like Data Science, Software Development, QA and Digital Marketing. You can ask doubt and get the answer for your queries from our experts.