In the previous tutorial we have seen how to iterate an array.
for (int i = 0; i <= 4; i++) { System.out.println(arr[i]); }
Now, let us see the easiest way to iterate an array.
We will create an Array with five values, Mohan, John, Paul, Kriti and Salim.
public class MyApplication { public static void main(String[] args) { String[] arr = {"Mohan", "John", "Paul", "Kriti", "Salim"}; for (String str : arr) { System.out.println(str); } } }
So, in the above code we have created a Array and initialised to the variable arr.
String[] arr = {"Mohan", "John", "Paul", "Kriti", "Salim"};
In the below way the values are positioned in the Array,
So, as we can see the elements are positioned as 0, 1, 2, 3 and 4.
Then we have the foreach loop.
for (String str : arr)
That takes the values of the array arr one by one and puts in the variable str.
Let us look at all the iterations of foreach loop.
for (String str : arr) { System.out.println(str); }
So, in the first Iteration, the first value i.e. Mohan is taken from the first location and put into the variable str.
And the print statement,
System.out.println(str);
Prints the value of str.
Then in the second Iteration, the second value i.e. John is taken from the second location and put into the variable str.
And the print statement,
System.out.println(str);
Prints the value of str.
Similarly, in 5 iterations all the values are printed.