next up previous
Next: While loops Up: The Frightened Freshers Guide Previous: if Statements

Arrays

And now for something completely different. So far you have learned about how to declare variables, store things into them, use if statements and do several other things with java. But what if you want to store more than 1 of something? Say you have a jar of sweets that can hold a certain number of sweets in little tiny boxes, wouldnt it be useful to be able to see what is inside each? Crazy kind of analogy, I know, but instead of declaring as many variables as there are boxes to hold sweets it is better to create an array.

An array is something that holds multiple values in a single variable. Yeah, sounds complex but I'll get there in a bit. Heres how you declare your array.
\begin{lstlisting}
datatype[] nameOfArray = new datatype[numberOfElements];
\end{lstlisting}

A few things to note about this. It looks similar to a variable declaration you've seen before, but instead it has a few new things tacked on. You have two square brackets after the datatype to tell Java that you want an array. Once you have got a name, you need to tell Java just how many things you want in your array. Another important thing is the new keyword.

Well, thats all fine and good, but what practical use does this have? Well, lets take another example. This time of a car. Our car has five seats, and these seats can be taken up by people who have names. From this, you know that you want an array and the names of people can be taken up using Strings. So, the code to declare your "car" would be:
\begin{lstlisting}
String[] car = new String[5];
\end{lstlisting}

Okay, so now we have a car! So how do we put people into the car? Well, its fairly similar to the variable assignment for ints, Strings and so on.
\begin{lstlisting}
nameOfArray[elementOfArray] = valueToStore;
\end{lstlisting}

So if one of the people wanted to sit in seat 2 then you could say:
\begin{lstlisting}
car[1] = ''John Smith'';
\end{lstlisting}

But wait, why did I put 1 and not 2? I said I wanted them to sit in seat 2! Well, this is something very very very important to do with Arrays. They start at 0. Yes, zero. Zilch. Nada. Nothing. If you tried to store something at position 5 in the array (car[5] = "whatever) then you would get an indexOutOfBoundsException thrown by the Java compiler.

So remember this well...arrays start at the number 0 not the number 1!

What if you wanted to fill the car with people called bob? Well, you could do the same as above on elements 0 through 4, but there is an easier way. This is where a loop comes in handy.


next up previous
Next: While loops Up: The Frightened Freshers Guide Previous: if Statements
Tom Carlson 2006-01-10