Java - Array Array Creation


All arrays in Java are objects.

You can create an array object using the new operator.


The general syntax for array creation expression is as follows:

Creates an array object of type ArrayDataType of ArrayLength length

new ArrayDataType[ArrayLength];

For example, you can create an array to store five int ids as follows:

new int[5];

5 is the length of the array, which is also called the dimension of the array.

The above expression creates an array object in memory, which allocates memory to store five integers.

To store the array object reference in empId, you can write

empId = new int[5];

You can combine the declaration of an array and its creation in one statement as

int[] empId = new int[5];

You can use an expression to specify the length of an array while creating the array.

int total = 3;
int[] array1 = new int[total];     // array1 has 3 elements
int[] array2 = new int[total * 3]; // array2 has 9 elements

Array is Object

Because all arrays are objects, their references can be assigned to a reference variable of the Object type.

For example,

int[] empId = new int[5]; // Create an array object
Object obj = empId;       // A valid assignment

Assume that obj is a reference of the Object type that holds a reference of int[]

int[] tempIds = (int[])obj;

Related Topics