Tutorial 5 Summary

So far, we have seen ways to store single pieces of information. However, to start to see the power of programming, we need to be able to handle collections of data. This is where arrays step in.

Imagine that you have a bunch of cardboard boxes, and you want to use them to store stuff. You put them on the floor, line them up, and number them in order. Let's label the first box "0", the second box "1", and so on. Yes, we are starting our counting from "0", but this is how we do things in Java, because we're strange like that. Now we can put things in the boxes. How exciting! Suppose we have some letters made out of styrofoam hanging around, and we want to put a letter in each box. Then we have something like the following:

Array and boxes example

Our analogy with cardboard boxes brings us to arrays. An array is a list of data, where each piece of data has a specific location in our list. The arrows in the above diagram point to a less colorful picture, consisting of a row of squares. This is how we usually think of arrays, but you can always imagine the boxes if you like that better. In the above example, each cell of the array stores one letter. If this is an array of strings, we could easily replace any of those letters with something like "dog" or "like used, slightly shotgunned". Also note the numbers under the array. Each number denotes where something is in the array, and we call each number an array index.

In Java, when we create an array, there are two things we must do. First, we need to tell Java what sorts of things we are going to put in the array. Each array can only hold one type of data, so we can create one array that holds Strings, and another array that holds ints, but not an array that holds both Strings and ints.

Second, we must tell Java how big our array is going to be, so we need to plan beforehand. As a general tip, try to conserve your array sizes. If you need an array that stores 10 elements, don't make an array of size 500 to do it; just keep it to size 10.

The following is the way we make a new array:

type[] myArray = new type[size];

In the above code, type can be any data type, like int or double or String. Of course, myArray can be replaced with any variable name you like. The word new must be there; don't worry about what it does now, but we will talk about that later. size is an integer stating how big you want the array to be.

An example array could be the following:

int[] myArray = new int[10];

This creates an array that can only hold ints, and makes the array have size 10 (in other words, there are 10 spots for holding things in the array). To actually use this array, we can put things in the array and get them out like so:

myArray[3] = 42;
int anotherNum = 76 + myArray[3];


Like the site?
Let people know:
Digg! StumbleUpon
			Toolbar del.icio.us