Thank you for visiting Blazing Games

Arrays

Arrays are a special type of variables. While arrays act like a method, they are slightly different. Arrays hold groups of variables. It is also possible to have arrays of arrays allowing for what is generally known as multi-dimensional arrays.

Arrays are created using the format

for example

Before an array variable can be used, it must be initialized. This is done by using the new keyword and by specifying the number of elements that the array has. An element is a value, so an array that holds 10 elements is essentially 10 variables compacted into one. An example of creating an array is

Once you have created an array, you can then access and modify the individual elements of an array. This is done by specifying which element you are referring to. This is where arrays can get confusing as elements are referenced starting with element 0 and ending with an element number one less than the size of the array. For instance, to set the 5th variable, which would be element number 4, of the list array to the number 7 we would use the following statement:

At this point in time arrays are not too important. Once we get into loops, however, arrays will become much more important. We will cover more advanced aspects of arrays in a future chapter.

You don't really need to know the following, but some of you may be interested. Computers generally store information as a series of bytes. Different data types require different amounts of bytes. A uni-code character, for instance, would use two bytes. An integer would use four bytes. An array is stored in memory as a large block of bytes. For instance, if you had an array of 10 integers, that array would allocate 40 bytes. The first four bytes would be array element 0, the second four bytes would be array element 1, and so on.

Multidimensional arrays can be handled in one of two ways. The first way would be to have consecutive blocks of memory. So a 10 by 10 integer array would allocate 400 bytes. The first 40 bytes contain the first block of elements, the next 40 contain the second block of elements, and so forth.

Java uses a slightly different method. It uses a reference method. The first dimension is allocated as a block of references (four bytes each). Each reference points to an array. The arrays are simply one dimensional arrays and store information that way. The advantage of this is that the size of the second dimension can vary from element to element. This is a very convenient feature.

Previous Chapter 3 Contents Page 8 of 10 Book Contents Next

About - Privacy Policy - Contact - Links - FAQ
Copyright © 2005-2006 Blazing Games Inc. All Rights Reserved