Iterating over Arrays in Java
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.
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;
for (i = 0 ; i < ar.length; i++) {
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.
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;
for ( int i : ar) {
x = i;
System.out.print(x + " " );
}
}
}
|
Output :
1 2 3 4 5 6 7 8
Last Updated :
11 Dec, 2018
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...