Creating Reference Arrays And Initializing Arrays

Creating Reference Arrays

You can create arrays of objects. You use the same syntax:

p = new Point[10];

This line creates an array of 10 references of type Point. However, it does not create 10 Point objects. Create these separately as follows:

1 public Point[] createArray() {

2 Point[] p;


4 p = new Point[10];

5 for ( int i=0; i<10; i++ ) {

6 p[i] = new Point(i, i+1);

7 }


9 return p;

10 }

This code generates an array in the heap memory with each array element filled with a reference to a Point object. The array in heap is shown in Figure 5-2.


Initializing Arrays

When you create an array, every element is initialized. In the case of the char array s in the previous section, each value is initialized to the null(‘\u0000’) character. In the case of the array p, each value is initialized to null, indicating that it does not (yet) refer to a Point object. After the assignment p[0] = new Point(), the first element of the array refers to a real Point object.

Note –
Initializing all variables, including elements of arrays, is essential to the security of the system. You must not use variables in an uninitialized state.

The Java programming language allows a shorthand that creates arrays with initial values:

String[] names = {





This code is equivalent to:

String[] names;

names = new String[3];

names[0] = “Georgianna”;

names[1] = “Jen”;

names[2] = “Simon”;

You can use this shorthand for any element type; for example:

MyDate[] dates = {

new MyDate(22, 7, 1964),

new MyDate(1, 1, 2000),

new MyDate(22, 12, 1964)