Arrays

Home | Graphical Version | Table of Contents | Next Chapter, "Making Decisions" | Previous Chapter, "Variables in Java"



Java programmers have a wide array of tools at their disposal. Among these, are arrays (sorry). An array allows you to store multiple related variables of the same type.
  1. What are arrays
  2. Declaring Arrays
  3. Using Arrays
  4. Multi-Dimensional Arrays



Declaring Arrays

Arrays allow you to store a list. For example, let's say you want to store the age's of several people. You can create an array.

Declaring Arrays

Declaring an array is easy enough; you just add double brackets ([]) to then end of the data type. Here is an example.

double[] Numbers;
int[] Ages;
float[] Stuff;
float[] StateSizes;

Next, you must fill your new variable. This calls for another example:

Numbers = new double[5];
Ages = new int[30];
Stuff = new float[78];
StateSizes = new float[50];

The numbers inside the brackets are the "dimensions" of the array. The dimensions are the number of elements in the array.

Using Arrays

Now you have a freshly declared array. So, how do you use it? Well, you can set any element of the array using brackets. Observe:

Numbers[3] = 104.493;
Ages[24] = 14;
Stuff[24] = 43.49
StateSizes[49] = Stuff[24] / 2; //This is Hawaii

Simple enough. You can assign values to as many elements in a list as you want.
I am sure a few of you have thought to yourselves, "You dolt, Hawaii is the fiftieth state, not the forty-nimth." Well maybe not in those words. First of all, I am not a dolt (just thought I would clear that up). Second of all, I am glad you noticed. The first element in Java is zero. That means the last element in an array with fifty elements is forty-nine. An array with fifty element does not have an element numbered fifty. You should always remember this. It is a common mistake for Java programmers.

Multi-Dimensional Arrays

In Java, you can make arrays of arrays. These are similar to multi-dimensional arrays, but not exactly the same. The difference is trivial however. Here is an example of a multi-dimensional array.

int[][] BoardSize = new int[2][4];

These arrays act pretty much like one-dimensional arrays.



Our next chapter will introduce you to the "if statement" - just another one of a vast array of tools available to Java programmers.

Home | Back to Top | Table of Contents | Next Chapter, "Making Decisions" | Previous Chapter, "Variables in Java"