In this section, you will learn how to use an array in Java.
Java Array Usage
We have already discussed that to refer an element within an
array, we use the [] operator. The [] operator takes an "int" operand and returns the element at that
index. We also know that the array indices start with zero, so the first element
will be held by the 0 index. For Example :-
int month =
months[4]; //get the 5th month (May)
Most of the times it is not known in the program that which elements are of interest in an array. To find the elements of interest in the program, it is required that the program must run a loop through the array. For this purpose "for" loop is used to examine each element in an array. For example :-
String months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "July", "Aug", "Sep", "Oct", "Nov", "Dec"}; //use the length attribute to get the number //of elements in an array for (int i = 0; i < months.length; i++ ) { System.out.println("month: " + month[i]); |
Here, we have taken an array of months which is,
String months[] =
{"Jan", "Feb", "Mar", "Apr",
"May", "Jun",
"July", "Aug", "Sep", "Oct",
"Nov", "Dec"};
Now, we run a for loop to print each element individually starting from the month "Jan".
for (int i = 0; i < months.length; i++ )
In this loop int i = 0; indicates that the loop starts from the 0th position of an array and goes upto the last position which is length-1, i < months.length; indicates the length of the array and i++ is used for the increment in the value of i which is i = i+1.