Witscale Test Center

7.4 Arrays > 7.4.1 Arrays declaration


7.4.1 Arrays declaration

An array is declared by specifying the datatype of elements it is going to hold. The array declaration is usually the data type followed by a pair of square brackets followed by the name of the array:  The general format is:

 

datatype[] arrayName;

 

The datatype can be a primitive or any valid Java type (class or interface type). An array of a primitive type int can be declared as,

 

int[] numbers;

 

Another way of declaring an array is to put the pair of square bracket after the arrayName as:

 

int numbers[];

 

Both declarations are valid. However, the first form is recommended as it has better readability. It is simpler to read int[] as an integer array. The second form, while reading from left to right may give a false impression of numbers as a variable of an int type only to realize later that it is in fact an array.

Arrays may also hold a collection of object references, provided they are of the same type. The declaration is similar to that of an array of primitive types:

      Date[] birthdates;

or

      Date birthdates[];

 

It is easy to see that the first form is more readable when we declare a method that returns an array. Let us consider  a method getNames() which returns a String array. It is legal but awkward to declare it as

 

String getNames()[] {}

 

However, it is more readable to declare getNames() as:

 

String[] getNames() {}

 

You can clearly read that the method returns a string array.

Array declaration in detail


Let us see what actually happens behind the scene in an array declaration. We have seen how the Java objects are created on heap, whereas the object reference variables and local variables of the object are created and stored on stack. When a variable of any type is declared, Java simply creates a placeholder on stack. We know that an array is an object. Like all the other Java objects, it has a reference. When an array is declared, only a reference variable that will hold a reference to the array object is created on stack. Array declaration does not mean that the array object is actually created. The declaration int[] intArray; implies that the reference variable intArray may hold a reference to the array of integers. Figure 7.4 shows the memory model after the intArray declaration.

 

Figure 7.4 Memory model after Array declaration

 

After the declaration, the stack will hold the intArray variable. As no array object is created yet the memory heap will be empty and the variable will not hold anything.