next up previous contents
Next: Composite operators Up: 4 Arrays, nested loops Previous: Creating an array   Contents

Array manipulation and references

To make use of the values stored in arrays you should refer to each element individually. The numbering of each element starts at zero, thus for vector1 above, the number 1.2 is the zeroth element vector1[0], 0.0 the first element vector1[1], and 5.3 the second element vector1[2], and so on. Individual array elements vector1[2] can then be used as any double variable would be, so you can for example assign a number to it, use it in a calculation, like this:

    System.out.print(vector1[1]);
    vector1[0] = 7;
    vector1[2] = vector1[0]*(-7.0) + vector1[3];

Often though you will want to perform the same or similar operations on all the entries of an array in turn. This can be done using loops, and shows the major advantage of an array over using many individual variables.

// create array called `list' and then print out elements to screen
int[] list = {1, 4, -3, 66, 19};
for (int i=0; i<5; i++)
{
    System.out.println(list[i]);
}

Which saves us typing out System.out.println(...) five times. Note that here the loop variable i runs from 0 to 4 as the elements of the array are numbered from zero. It is a very common mistake to let the loop variable increase to too high a value. For example it would be easy to type i<=5 by mistake, by thinking about the array having five entries. If a variable does go beyond the end of an array, the error will not be picked up by the compiler, but instead results in an ArrayIndexOutOfBoundsException when the code is executed. Also be careful to start with int i = 0 to use the first array entry.

// create array of general length filled with random no.s
double[] randomNos = new double[N]; // value of N set somewhere prev.
for (int i=0; i<N; i++)
{
    randomNos[i] = Math.random();
}

In this example the loop not only saved us typing randomNos[...] = Math.random(); many times (N could be 10, 1000, 100000 or more!), but in fact we don't even need to know whether the array is 10 or 100000 long, so long as we have the value stored in N.

If you wish to use the length of any array in your code, append .length to the end of the name of the array. For example the value of list.length would be 5 or randomNos.length would be the value of N. In the former case it is best to use list.length instead of typing 5 explicitly because it makes the code more general and requires less alteration if the length of the array were altered in a second version of the program.

Exercise 4.1


(5 marks)



The aim of this exercise is to practice using arrays in loops and accessing individual array elements.

Write a program, `Arrays', that creates an array of length N, where N is an int you declare and set in the program. You will now fill the array with the first N numbers of the Fibonacci sequence. This is a sequence which crops up frequently in nature. The first two numbers are 1, then the rule to compute the rest is that each number is the sum of the two previous, i.e.

x1 = 1,   x2 = 1,   xn = xn-1 + xn-2 (1)
The resulting sequence is 1, 1, 2, 3, 5, 8, 13,....

At the END of your program, print out the first ten numbers of the sequence using a loop. Separately it should also print out the 30th and 46th numbers in the sequence. A print-out of your program and sample output should go in your lab notebook.



What if you want to create a new array which contains the same values as an existing array? You may be tempted to type double[] b = a where a is the array to be copied to the new array b. This is valid code, but it has a slightly different effect to the one desired. In order to create a copy of an array you should use a for loop and set each value individually:

// create array b of same length as array a
double[] b = new double[a.length];

// set each value of b equal to equivalent value of a
for (int i=0; i<a.length; i++)
{
    b[i] = a[i];
}

Exercise 4.2


(5 marks)



Copy the java program ArrayCopyDemo.java from the course web site8. Read the code and try to predict what it will do. When you have decided, compile it and run it. Comment on the different effects of the two copying methods and explain what has happened.



For a usual variables, double b = a, copies the value of a to b. With arrays, this is not the case. Instead, b is set to to refer to the same data that a refers to. There is therefore still only one copy of the data so any change to the values of b is a change to the values of a. This is due to arrays being reference data types, that is they are handled by reference, unlike int, double, boolean etc. which are primitive data types, handled by value. For example in int[] list = {1, 4, 3} the array {1, 4, 3} is stored somewhere in the computer's memory, and list is a variable name that refers to it, but we might set other variable names to refer to this same area of memory using the = operator. For now it is hard to see the advantage of arrays behaving in this way, but some should become clear in later sections.

Note that anything created with a new command, not just arrays, is a reference data type.

Figure 4.2 illustrates what happens when you assign one array to another.

Figure 4.2: What happens when array a is defined and then array b is set equal to a? Since a and b are references, they both point to the same array data (bottom left). It is important to understand that b does not get its own copy of the array data (bottom right).
\includegraphics[width=12cm]{arraycopy}

The only other strange behaviour of reference data types to be aware of at this stage is that of the == comparison operator.

double[] a = {1.0, 2.0, 3.0, 4.0}
double[] b = {1.0, 2.0, 3.0, 4.0}

if (a == b)
{
    // code here not executed
}

Rather than comparing the values of a and b, their references are compared -- that is the code asks whether a and b refer to the same area of memory. So even though they have the same values the test a == b will be false and the code within if never executed.

Conversely, if the references are both to the same data, then they are considered to be equal so the comparison will be true:

double[] a = {1.0, 2.0, 3.0, 4.0}
double[] b = a

if (a == b)
{
    // code here always executed, a==b true!
    // both references refer to same array
}


next up previous contents
Next: Composite operators Up: 4 Arrays, nested loops Previous: Creating an array   Contents
RHUL Dept. of Physics