Java-Array

Array

So far we have used only the primitive data types, namely charintfloat and double. Although these types are very useful, they are constrained by the fact that a variable of these types can store only one value at any given time. Therefore, they can be used only to handle limited amounts of data. In many applications, however, we need to handle a large volume of data in terms of reading, processing and printing. To process such large amounts of data, we need a powerful data type that would facilitate efficient storing, accessing and manipulation of data items. Java supports a data type known as array that can be used for such applications.

An array is a group of contiguous or related data items that share a common name. For instance, we can define an array name mark to represent a set of marks of a group of students. A particular value is indicated by writing a number called index number or subscript in brackets after the array name. For example, mark[6] represents the mark of the 6th student. While the complete set of values is referred to as an array, the individual values are called elements. Arrays can be of any variable type.

The ability to use a single name to represent a collection of items and to refer to an item by specifying the item number enables us to develop concise and efficient programs.

Creation of Arrays

You declare an array variable by specifying the array type which is the element type followed by [ ] and the array variable name. For example, here is the declaration of an array mark of integers :

array

However, int[ ] mark statement only declares the variable mark. It does not yet initialize mark with an actual array. You use the new operator to create the array.

2

The new int[5] statement sets up an array that can hold 5 integers.

Initialization of Arrays

The final step is put values into the array created. This process is known as initialization. This is done using the array subscripts as shown below :

3

Note that Java creates arrays starting with the subscript of 0 and ends with a value one less than the array size specified.

Program 

Program Source 

public class Javaapp {
 
    public static void main(String[] args) {
     
        int[] array = new int[5];
        array[0] = 20;
        array[1] = 40;
        array[2] = 60;
        System.out.println("array[0] = "+array[0]);
        System.out.println("array[1] = "+array[1]);
        System.out.println("array[2] = "+array[2]);
    }
}

Leave a Comment