Thursday 13 September 2012

Arrays in Java

An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed. You've seen an example of arrays already, in the mainmethod of the "Hello World!" application. This section discusses arrays in greater detail.


An array of ten elements


class ArrayDemo {
public static void main (String[ ] args){
//declares an array of integers
Int [ ] anArray;
//allocates memory for 3 integers
anArray = new int[10];
//initialize first element
anArray[0] = 100;
//etc.
anArray[1] = 200;
anArray[2] = 300;

System.out.println(“Element at index 0: ” + anArray[0]);
System.out.println(“Element at index 1: ” + anArray[1]);
System.out.println(“Element at index 2: ” + anArray[2]);              
}   
}

The output from this program is:

Element at index 0: 100
Element at index 1: 200
Element at index 2: 300