Introduction to array in Java

An array is a data structure that defines an indexed collection of a fixed number of homogeneous data elements. It means that all elements in the array have the same data type. A position in an array is indicated by a non-negative integer value called the index. An element at a given position in the array is accessed using the index. The size of an array is fixed and cannot be increased to accommodate more elements.

In Java, arrays are objects. Arrays can be of primitive data types or reference types. Each array object has a final field called length, which specifies the array size i.e. the number of elements that the array can accommodate. The first element is always at index 0 and the last element is at index n-1, where n is the value of the length field in the array.

array in java

The above diagram consists of an array with ten values, each value in an array is called an element, and each element is accessed by its numerical index. In the above diagram, numbering begins with 0. The 9th element can be accessed at index 8.

Simple arrays are one-dimensional arrays i.e. a simple sequence of values. Since arrays can store object references, the objects referenced can also be array objects. This implements arrays of arrays.

The following program ArrayDemo creates an array of integers and puts some value in it. It also prints each value to standard output.

Program to create an array of integers and initialize it.

class ArrayDemo
    public static void main(String args[])
        int[] anArray;      // declares an array of integers
        anArray = new int[10];  // allocates memory for 10 integers
        anArray[0] = 100;       // initialize first element
        anArray[1] = 200;       // initialize second element
        anArray[2] = 300;       // etc.
        anArray[3] = 400;
        anArray[4] = 500;
        anArray[5] = 600;
        anArray[6] = 700;
        anArray[7] = 800;
        anArray[8] = 900;
        anArray[9] = 1000;
        System.out.println("Element ay index 0: " + anArray[0]);
        System.out.println("Element ay index 1: " + anArray[1]);
        System.out.println("Element ay index 2: " + anArray[2]);
        System.out.println("Element ay index 3: " + anArray[3]);
        System.out.println("Element ay index 4: " + anArray[4]);
        System.out.println("Element ay index 5: " + anArray[5]);
        System.out.println("Element ay index 6: " + anArray[6]);
        System.out.println("Element ay index 7: " + anArray[7]);
        System.out.println("Element ay index 8: " + anArray[8]);
        System.out.println("Element ay index 9: " + anArray[9]);

The output of the program is:

Element ay index 0: 100
Element ay index 1: 200
Element ay index 2: 300
Element ay index 3: 400
Element ay index 4: 500
Element ay index 5: 600
Element ay index 6: 700
Element ay index 7: 800
Element ay index 8: 900
Element ay index 9: 1000

Leave a Reply