Home Java Beginners Arrayexamples Java Array Usage
Questions:Ask|Latest


 
 

Share on Google+Share on Google+

Java Array Usage

Advertisement
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 :-
i
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.

 

Advertisements

Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: May 28, 2007

Ask Questions?    Discuss: Java Array Usage   View All Comments

Post your Comment


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

I know this is an old page (May of 2007)... But on your page: http://www.roseindia.net/java/beginners/arrayexamples/java_array_usage.shtml 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.
sumit
March 26, 2012
java

sent 2d array program with output
DMCA.com