Open In App
Related Articles

Iterating over Arrays in Java

Improve Article
Improve
Save Article
Save
Like Article
Like

Iterating over an array means accessing each element of array one by one. There may be many ways of iterating over an array in Java, below are some simple ways.

Method 1: Using for loop:
This is the simplest of all where we just have to use a for loop where a counter variable accesses each element one by one.




// Java program to iterate over an array
// using for loop
import java.io.*;
class GFG {
  
    public static void main(String args[]) throws IOException
    {
        int ar[] = { 1, 2, 3, 4, 5, 6, 7, 8 };
        int i, x;
  
        // iterating over an array
        for (i = 0; i < ar.length; i++) {
  
            // accessing each element of array
            x = ar[i];
            System.out.print(x + " ");
        }
    }
}


Output :

1 2 3 4 5 6 7 8 

Method 2: Using for each loop :
For each loop optimizes the code, save typing and time.




// JAVA program to iterate over an array
// using for loop
import java.io.*;
class GFG {
  
    public static void main(String args[]) throws IOException
    {
        int ar[] = { 1, 2, 3, 4, 5, 6, 7, 8 };
        int x;
  
        // iterating over an array
        for (int i : ar) {
  
            // accessing each element of array
            x = i;
            System.out.print(x + " ");
        }
    }
}


Output :

1 2 3 4 5 6 7 8 

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

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.


Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 11 Dec, 2018
Like Article
Save Article
Similar Reads
Related Tutorials