We have already learned about Java for loop and for-each loop. And in the last chapter we learned about array and array length. Using these concept we will access all the element in an array.
Array in java is index based. And the index is start from 0 and the last index is ( length - 1 )
String[] favourite_languages = {"Java", "Kotlin", "C++", "Python", "JavaScript", "Php"};
In this example, array starting index is 0 and the last index is 5.
Last index = length - 1 . ( Here length is 6) so the last index is 5.
We need to be careful while accessing array elements. Because if we try to access an array element which does not exist in the array then our program will get an error.
Loop through the array using for loop :
String[] favourite_languages = {"Java", "Kotlin", "C++", "Python", "JavaScript", "Php"};
for( int i = 0; i < favourite_languages.length; i++){
System.out.println("Value of " + i + " index = " +favourite_languages[i]);
}
Output:
Value of 0 index = Java Value of 1 index = Kotlin Value of 2 index = C++ Value of 3 index = Python Value of 4 index = JavaScript Value of 5 index = Php
In this example, we start or initialize the loop from 0 because of array's first index is 0 and the condition is the variable i is less than favourite_languages length and lastly increment the i value by 1. The condition tells that if the i value is 0 - 5 then return true otherwise return false. when the i value reaches 6 the condition will be false and the loop will break.
Loop through the array using for-each loop :
String[] favourite_languages = {"Java", "Kotlin", "C++", "Python", "JavaScript", "Php"};for (String language: favourite_languages){
System.out.println(language);
}
Output:
Java Kotlin C++ Python JavaScript Php
In this example , We don't have to tell the loop where to start and where to end. This is done by for-each itself. for-each loop is easier than the for loop. The for-each loop syntax is so easy. First, define the data type of array and give a variable name where the array element come dynamically. Then use colon ( : ) after the colon and write the array name. We can access the array elements using this variable