Main Content

Java is a dynamic language .... (and comparison)

Archive - Originally posted on "The Horse's Mouth" - 2008-01-08 23:29:41 - Graham Ellis

Many older programmers are used to setting up an array of a fixed size and saying "that's fixed" ... for the duration of the program, if not for all time until the application is recompiled.

Languages such as C gave us malloc, calloc and realloc (and things have progress on somewhat in C++) to let us dynamically set up arrays, and languages like Perl and Python have move on to lists which are totally different structures. PHP uses the word "array" but really they are lists!

An array (in computer science terms) is defined as sequential memory locations and so by definition if you run off the end of it, you're going to be "out of bounds" and something nasty will happen. A list is defined as a series of items linked on to each other in sequence, which can be extended later.

What about Java?

Java uses arrays. However, they can be dynamically allocated so that the size can be controlled at run time, and all Java arrays are objects which means that you can re-allocate a name that you've already used to a new block of memory or another differing array as your program runs - thus getting a far more dynamic effect.

Example?


Let's calculate a result that processes an array to produce a new and longer array many times over.

Initialization and setup:

int [] previous, current;
previous = new int[0];


The names current and previous are set up in the first line, but with no particular size. Then previous is set to an empty array with no elements, basically to keep the compiler happy.

Let's now run the iteration loop:

for (int k=0; k<rows; k++) {
current = new int[previous.length+1];


We're going through the loop as many times as necessary, setting up the current row to be one longer than the previous.

At this point, calculations to generate current from previous!

Finally, set "previous" to be the array named in "current". The old previous will be lost and the memory released collected up in due course by the garbage collector, and we can run around the loop again to calculate the next row.

previous = current;
}


This "moving up" is cheap - we're only moving up a reference or pointer - a single memory address - and not what could be a major piece of storage. We're renaming a town, not building a complete new one if you like!

There's a complete program example here which shows Pascal's triangle being generated with this dynamic technique.

For even greater flexibility, see java.lang.util