Tackling Arrays
By Al Williams
If you mainly write applets for the Web, it's easy to forget that Java is a full-blown object-oriented language. That means it has lots of features that applet writers often overlook. This is especially true of features that work differently from the way they do in other languages you've used before.
Take arrays, for example. While most programmers are familiar with arrays, Java implements them very differently from the way other languages do. In addition to arrays, Java also offers objects that manage lists, such as the Vector object.
Start at the Beginning
Conceptually, arrays are variables that hold more than one item of a particular type. For example, let's say you have a list of four integers in an array and you want to average them. If you kept them in normal variables, your code would look like that in
Example 1(a).
While this will work, it isn't very good code. What happens when you want to average more than one list of items? How could you write a general-purpose function to compute averages regardless of how many items you supply? Arrays solve this problem.
Java uses a variable name followed by square brackets to specify an array. Inside the square brackets, you enter the element number (starting with 0) that you want to access (this number is the array index).