Java Reference
In-Depth Information
Continuing with our discussion, you can now create an array to store five
int
employee ids as follows:
new int[5];
In this expression, 5 is the length of the array (also called the dimension of the array). The word “dimension” is
also used in another context. You can have an array of dimension one, two, three, or more. An array with more than
one dimension is called a multi-dimensional array. I will cover the multi-dimensional array later in this chapter.
In this topic, I will refer to 5 in the above expression as the length of the array, not as the dimension of the array.
Note that the above expression creates an array object in memory, which allocates memory to store five integers.
The
new
operator returns the reference of the new object in memory. If you want to use this object later in your code,
you must store that reference in an object reference variable. The reference variable type must match the type of
object reference returned by the
new
operator. In the above case, the
new
operator will return an object reference of
int
array type. You have already seen how to declare a reference variable of
int
array type. It is declared as
int[] empId;
To store the array object reference in
empId
, you can write
empId = new int[5];
You can also combine the declaration of an array and its creation in one statement as
int[] empId = new int[5];
How would you create an array to store 252 employee ids? You can do this as
int[] empId = new int[252];
You can also use an expression to specify the length of an array while creating the array.
int total = 23;
int[] array1 = new int[total]; // array1 has 23 elements
int[] array2 = new int[total * 3]; // array2 has 69 elements
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
However, if you have the reference of an array in a reference variable of the
Object
type, you need to cast it to the
appropriate array type before you can assign it to an array reference variable or access elements by index. Remember
that every array is an object. However, not every object is necessarily an array.
// Assume that obj is a reference of the Object type that holds a reference of int[]
int[] tempIds = (int[])obj;