Java Program to Iterate Over Arrays Using for and foreach Loop

An array is a group of like-typed variables that are referred to by a common name. Arrays in Java work differently than they do in C/C++. Here, we have explained the for loop and foreach loop to display the elements of an array in Java.

1. For Loop:

For-loop provides a concise way of writing the loop structure. A for statement consumes the initialization, condition, and increment/decrement in one line thereby providing a shorter, easy to debug structure of looping.

Syntax:

for (initialization; test condition; 
                              increment/decrement)
{
    // statements
}
  • Initialization: Executed before the execution of the code block. An already declared variable can be used or a variable can be declared, local to loop only.
  • Test Condition: Testing the exit condition for a loop and return a boolean value. The test condition is checked prior to the execution of the loop statements.
  • Statement execution: Once the condition is evaluated to true, the statements in the loop body are executed.
  • Increment/ Decrement: It is used for updating the variable for the next iteration.

Time Complexity: If the statements are O(1), the total time for the for loop: N*O(1), O(N) overall.

2. For Each Loop:

For-each is an array traversing technique like for loop, while loop, do-while loop introduced in Java5.



  1. It starts with the keyword for like a normal for-loop.
  2. Instead of declaring and initializing a loop counter variable, you declare a variable that is the same type as the base type of the array, followed by a colon, which is then followed by the array name.
  3. In the loop body, you can use the loop variable you created rather than using an indexed array element.
  4. It’s commonly used to iterate over an array or a Collections class (eg, ArrayList).

Syntax

for (type var : array) 
{ 
    //statements
}

Time Complexity: O(n) where n is the number of elements iterated.

Difference between for loop and for-each() loop in Java.

For Loop

For Each Loop

1. Increment/Decrement statement is required.

e.g i=i+3

1. Counter always gets incremented by 1, cannot iterate in decremental order  
2. It is appropriate when data in the array needs to modify. 2. Not appropriate when data in the array needs to modify.
3. It keeps track of index, such that an array index can be obtained.  3. It doesn’t keep track of index, such that an array index can’t be obtained.

Iteration in List:

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java for and foreach loop in list
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
  
public class App {
  
    public static void main(String args[])
    {
        // creating array list
        List<String> tech = new ArrayList<>(Arrays.asList(
            "Mac", "Samsung Gear ", "iPhone 12+"));
  
        // iterating over List using for loop
        System.out.println(
            "iterating over a List using for loop in Java:");
        for (int i = 0; i < tech.size(); i++) {
            System.out.println(tech.get(i));
        }
  
        // iterating over List using for Eachloop()
        System.out.println(
            "iterating over a List using  forEach() loop in Java:");
        for (String gadget : tech) {
            System.out.println(gadget);
        }
    }
}

chevron_right


Output

iterating over a List using for loop in Java:
Mac
Samsung Gear 
iPhone 12+
iterating over a List using  forEach() loop in Java:
Mac
Samsung Gear 
iPhone 12+

Iteration in an array:

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java Program for Iteration in Array
public class GFG {
    
    public static void main(String args[])
    {
        // created array
        int[] element = {1, 9, 27, 28, 48}; 
        
       // iterating over an array using for loop
        System.out.println(
            "iterating over an array using for loop in Java:");
        
        for (int i = 0; i < element.length; i++) {
            System.out.println(element[i]);
        
        
        // iterating over an array using  forEach() loop
        System.out.println(
            "iterating over an array using forEach() loop in Java:");
        for (int var : element) { // synatx forEach() loop
                                  // var is variable.
            System.out.println(var);
        }
    }
}

chevron_right


Output

iterating over an array using for loop in Java:
1
9
27
28
48
iterating over an array using forEach() loop in Java:
1
9
27
28
48

Attention reader! Don’t stop learning now. Get hold of all the important Java and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.