This feature, however, is also one of the limitations of arrays. Once the space is allocated, it cannot be extended. There is no guarantee that the next block of memory will be free at some time later in the execution of the program. In this sense arrays are static data structures.
On the other hand, arrays can be allocated dynamically in Java. This contrasts with a number of programming languages in which all array sizes must be known at compile time. This is not true of Java. The following, for example, is valid:
int n = 20; int a[] = new int[n];Although n was initialised here at declaration, it could equally have been set in any way during program execution, e.g. as a consequence of file or keyboard input. It is still true, however, that once space has been allocated, it cannot be extended.
In order to overcome this limitation, Java provides a Vector class in the java.util package which effectively provides arrays that can grow or shrink dynamically. In reality, however, once the array is full, another larger array is created and the contents of the first are copied into the second; but this is opaque to the user. We shall need a facility like this when dealing with stacks and queues. But it will be clearer to write the simple code necessary explicitly when it is needed.