1
0

## Declaring Array in Java

The above program declares an array with the following line of code:

int[] anArray;  // declares an array

The same statement may be written in a slightly different way as:

int anArray[];

Hence, array variable declaration has the following syntax:

<element-type> [] <array-name>;

Or

<element-type> <array-name> [];

Where <element-type> can be primitive-data type or a reference type. The array-variable <array-name> has the type <element-type>[]. Note that the array size is not specified. This means that the array-variable <array-name> can be assigned an array of any length, as long as its elements have <element-type>. It is important to note that declaration doesn’t actually create an array, only declares a reference that can denote an array object:

int anArray[], number;
Student[] st, data;

These two declarations declare an anArray and st to be reference variables that can denote arrays of int values and arrays of Student objects respectively. The variable data can denote an array of Student but the variable number cannot denote an array of int values. It is simply an int-type variable. When the [] notation follows the type, all the variables in the declaration are arrays.

An array can be constructed for a specific number of elements of the element type, using the new operator. The resulting array reference can be assigned to an array variable of the corresponding type:

<array-name>= new <element-type> [<array-size>];

The minimum value of array-size is 0. if the array size is negative, a NegativeArraySizeException arises. The array can be constructed as follows:

anArray = new int[10];  // An array of 10 integers
st = new Student[20];   // An array of 20 student data

The array declaration and construction can be combined together as follows:

<element-type>[] <array-name> = new <element-type>[<array-size>];

OR

<element-type> <array-name>[] = new <element-type>[<array-size>];

here, in the above declaration array elements are initialized to their default values i.e. 0 in case of int array and ‘NULL’ value in case of Student array e.g.

int[] IntArray = new int[10];   //Default element value is 0
Student[] st = new Student[10]  //Default element value is NULL

once an array has been constructed, its elements can also be explicitly initialized individually.