English
312.04
To:
Computer Science Professional
From:
John Sharkey
Subject:
The declaration of arrays while programming in Java
Date:
September 16, 1998
The
declaration of an array of primitive types
An
array is an object, so when the array declaration is given, no memory is yet
allocated to store the array. The declaration example that I am going to use
is:
int [ ] array1;
array1 is a reference for an array, and at this
point is null. To declare 100 ints, we issue a new command. An example of this
is:
array1 = new int [ 100 ];
Now array1 references an array of 100 ints. There are other ways to declare arrays in
Java. Some examples of this are:
int [ ] array1 = new int [ 100 ];
or
int [ ] array1 = { 1, 2, 3, 4 };
In Java, the brackets that are used can go
before or after the array name. Putting the brackets before the array name (as
shown above) is a better programming style.
The
declaration of an array of objects
To
declare an array of objects uses the same syntax. However, when programmers
allocate an array of objects, each object initially stores a null reference.
Each must be set to reference a constructed object.
An example of an array of 5 buttons is
constructed as follows:
Button [ ] arrayOfButtons;
arrayOfButtons = new Button [5];
for (int j = 0; j < arrayOfButtons.length; j
++ )
arrayOfButtons [ j ] = new Button( );
This is a prefect example of declaring an array
of objects in Java. Above, arrayOfButtons is an array of type Button. The
Button is set to have 5 buttons and set to variable name arrayOfButtons. Next
is the for loop (which uses j as its loop variable) which runs from 0 to the
length of arrayOfButtons (which is 5).