Hooray for Arrays! |
Hello, and welcome to the official guide to using arrays in Java (veterans of the site might remember My Friend Fred). Thanks to Alex Young for the fantastic title.
So you don't know what an array even is? Well, it's a collection of the same type of variable. For example we can have an array of ten
int
s. We only have to say which of them we want, and then we can treat it like any other variable. We could use an array ofString
s to store the names of all our friends. Let's do that.
class Hello { public static void main(String[] args) { String a = "Dave"; String b = "Pete"; System.out.println("My friends are " + a + " and " + b); } }I think you can guess what this program does...
[nurmes]btg: javac Hello.java [nurmes]btg: java Hello My friends are Dave and Pete [nurmes]btg:We haven't even used an array yet, and isn't it fun already! This version has two separate variables, with two separate names (they are called
a
andb
). With an array there is just one name for the whole thing, and we have to use numbers to get different people's names.
class Hello { public static void main(String[] args) { String[] mates; } }Instead of being a variable of type
String
, this is a variable of typeString[]
(meaning string array). The name of the variable ismates
. We haven't put anything in the variable yet (like if we'd writtenint i;
).In order to put something in the variable, we have to decide what size of array we want. The size of an array is fixed when we create it - in order to make a bigger or smaller one, we need a new array altogether. However, we can put a new array (of a different size) into the variable
mates
, causing it to apparently change size.But don't worry about that yet. Let's make an array with space for just two people:
class Hello { public static void main(String[] args) { String[] mates = new String[2]; } }Now
mates
contains an array with space for twoString
s, although neither of them contains anything. To create an array we just writenew
then the type of thing we want the array to contain (String
), and then the size of array between square brackets.Now an array with nothing in is pretty useless; let's bring back my two friends:
class Hello { public static void main(String[] args) { String[] mates = new String[2]; mates[0] = "Dave"; mates[1] = "Pete"; } }We write the name of the variable and square brackets containing a whole number, to say which element of an array we want to use. Then we can print out the value, or store a value in, just like any other variable.
The elements of an array are always numbered starting from zero. So if I had 20 mates, they would be stored in
mates[0]
up tomates[19]
. The number in the square brackets is called the array index.As it is, I only have two mates - let's print out both of their names to make me feel better:
class Hello { public static void main(String[] args) { String[] mates = new String[2]; mates[0] = "Dave"; mates[1] = "Pete"; System.out.println("My friends are " + mates[0]+ " and " + mates[1]); } }Now let's try it.
[nurmes]btg: javac Hello.java [nurmes]btg: java Hello My friends are Dave and Pete [nurmes]btg:Congratulations, you've just written your first program using an array. Arrays really aren't all that exciting - they are just a numbered list of variables with the same type. But we can use them to process hundreds or thousands of pieces of information the same way.
When we put the two friends' names into the array, this is called initialising it (which just means giving it initial, or starting values). There is another more convenient way to initialise an array; try this:
class Hello { public static void main(String[] args) { String[] mates = { "Dave", "Pete" }; System.out.println("My friends are " + mates[0]+ " and " + mates[1]); } }Notice that we don't need to write
new String[2]
any more. In fact, nowhere have we said that we want to have an array of two strings. The array is made just the right size for the number of names we put in it. Try this one for yourself.It's important that we don't try to access elements of an array which don't exist. Remember that the array always starts at zero (so negative numbers aren't allowed) and goes up to one less than its size. If we try to access an element outside of the array, the program will have problems when we try to run it.
class Hello { public static void main(String[] args) { String[] mates = { "Dave", "Pete" }; System.out.println("My friends are " + mates[0]+ " and " + mates[2]); } }Now we are trying to access
mates[2]
which isn't allowed (even though the array has size 2, it doesn't have an element at the index 2).
[nurmes]btg: javac Hello.java [nurmes]btg: java Hello Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException at Arrays.main(Arrays.java:8) [nurmes]btg:Notice that the exception occurs when we run the program, not when we compile it. The exact message might be different for you, but it is always an
ArrayIndexOutOfBoundsException
. I'll explain about exceptions in a later lesson.I'm going to change the way the example works slightly, using a
for
loop. For this you need to have read the lessonGoing Loopy. If you haven't, please go back and look at that first.
class Hello { public static void main(String[] args) { String[] mates = { "Dave", "Pete" }; System.out.println("My friends are:"); for (int i = 0; i < 2; i++) { System.out.println(mates[i]); } } }The value of
i
goes through all the valid indices for the array - in this case just the values0
and1
. If you're unhappy about how this works, go back and look atGoing Loopy again.
[nurmes]btg: javac Hello.java [nurmes]btg: java Hello My friends are: Dave Pete [nurmes]btg:Now suppose you want to write a program which works with an array you don't know the size of when you write the program. Say the list of friends is entered by the user - you have no idea how many friends they have. But you need to know the length of the array, to avoid going over the end as we just did before, because that causes errors.
The solution is simply to ask the array what its length is! I'll show you with an example, which prints out the list of my friends without knowing in advance how many of them there are.
class Hello { public static void main(String[] args) { String[] mates = { "Dave", "Pete" }; System.out.println("My friends are:"); for (int i = 0; i < mates.length; i++) { System.out.println(mates[i]); } } }The value of
mates.length
is the size of the array (2 in this case). See that we now haven't written the number 2 in the program anywhere at all. It's crucial to remember that the elements of the array are numbered 0 and 1, which is why we use a<
symbol rather than a<=
.
[nurmes]btg: javac Hello.java [nurmes]btg: java Hello My friends are: Dave Pete [nurmes]btg:Now we can modify the list of friends to our heart's content, and the program will still work. Try it yourself. I'm going to add some girls to my list. Just make sure that all the different names are separated by a comma (so the last one doesn't need a comma following it). Remember that the compiler doesn't care about new lines and spaces. To make the point, I will put my new friends on the same line as each other.
class Hello { public static void main(String[] args) { String[] mates = { "Dave", "Pete", "Sue", "Mandy" }; System.out.println("My friends are:"); for (int i = 0; i < mates.length; i++) { System.out.println(mates[i]); } } }Yet again, we haven't written anywhere that we have four friends, but because the program uses
mates.length
it doesn't matter.
[nurmes]btg: javac Hello.java [nurmes]btg: java Hello My friends are: Dave Pete Sue Mandy [nurmes]btg:We can have arrays of all sorts of different types of things. As an example, I'm going to modify this program to print out the beginning of the seven times table.
class Hello { public static void main(String[] args) { int[] tables = { 7, 14, 21, 28, 35, 42 }; System.out.println("The seven times table is:"); for (int i = 0; i < tables.length; i++) { System.out.println(tables[i]); } } }All that we've really changed is the name of the array, and the contents of it (which now have to be numbers, as it is an array of
int
s).
[nurmes]btg: javac Hello.java [nurmes]btg: java Hello The seven times table is: 7 14 21 28 35 42 [nurmes]btg:Try messing around and making your own programs using arrays and
for
loops. Don't worry about making mistakes - I've shown you pretty much all the things which can go wrong.Well I hope you enjoyed this lesson - fill out the questionnaire and we'll get on to something else.
Baby You Can Turn Me On
Too patronising? Too complex? Typing error? Offended by traffic cones?
Got a question or something I should add? Send an email to ben_golding@yahoo.co.uk !
visits to this site
The contents of this site are copyright of Ben Golding