Java Array Usage

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 :-
nt 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.


Share on Google+Share on Google+

Java Array Usage

Posted on: May 28, 2007 If you enjoyed this post then why not add us on Google+? Add us to your Circles



Discuss: Java Array Usage   View All Comments

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
Ian Moone
February 8, 2012
Java Array

I know this is an old page (May of 2007)... But on your page: In the code example you are calling the Array Variable name of 'month' when it was initialized as 'months'. I know it's a small problem but I thought it should be pointed out.
March 26, 2012

sent 2d array program with output