Sunday, 17 April 2016

Java Tutorial 6 - Arrays

Last Time
Last time we looked at comments. More importantly, the time before, we learnt about variables and that they can be used as a container to hold a value for the duration of the program

Today we're going to learn what arrays are, what they're used for and how to use them

What's an array
An array is a variable which holds more than one value, it holds a list of values. For example, I could have an array containing the names of everyone in a school
An array can be an array of String, an array of ints, or an array of anything else

Why are they useful
They are used when we need to store lots of data of the same type. For example I might want to store a list of names, a list of places, countries, cars, basically anything

How to use them
Remeber an array can contain string, ints or anything else, but not a mixture. First we need to decide what our array is going to contain.
For this example, we'll be making an array of names containing Amy, Bob, Charlotte, Dave, Emma and Frank, so it will be Strings
Declare the array like so

String[] names = {"Amy", "Bob", "Charlotte", "Dave", "Emma", "Frank"};

The String[] means this variable is going to be an array of strings
The array is called names
It contains the items wrapped in the curly braces, separated by commas

Accessing the values of an array
To print or modify the value of a certain item in an array we use it's index
The index of an item is it's position, counting from 0
So in this example, Amy has index 0, Bob's index is 1, Frank is 5 etc

To access a value we use the name of the array followed by the index is square brackets like so:


So to print the name with index 3 we would use


This should print Dave

Similarly, we can change the value of an index by reassigning it

names[3] = "David"

Now when we do

We get David instead of Dave

For clarity here is the full code, commented

  String[] names = { "Amy", "Bob", "Charlotte", "Dave", "Emma", "Frank" }; // This line defines the array

  System.out.println(names[3]); // This should print Dave
  names[3] = "David"; // This changes Dave to David
  System.out.println(names[3]); // This should now print David

That's the end of this tutorial, next time we'll look at conditional statements