Java

TOPIC 44 – INTRO TO ARRAYS

 

 

LESSON NOTE

 

 

INTRO

In advanced programs, we often need to create a lot of variables.  Consider Tic Tac Toe, we’d need to create 9 variables for the nine squares on the board game.  Now consider a game like Checkers, we’d need 64 variables to hold the state of each square on the board.  Or perhaps a game of S-O-S – hundreds of variables!  This would be very inconvenient to deal with…

 

Instead of creating an inconvenient number of variables of the same type, we can use arrays. 


DEFINITION & TERMINOLOGY

 

Arrays are simply a sequence of variables of the same type stored together in memory.

 

Each variable in the array is called an element.  To identify one element from another, we give each one a number called an index.

 

The total number of elements in an array is referred to as the array’s size or length.

 

To really understand all of this, we need to look at the required coding and examples.

CREATING AN ARRAY

 

In general, to create an array, we use:

 

            dataType[] arrayName = new dataType[size];

 

Example 1 – Create an int array called age of length 6.

 

     int[] age = new int[6];

 

Example 2 – Create a Boolean array called coco that can store 10 values.

 

            boolean[] coco = new boolean[10];

 

ARRAYS IN MEMORY

 

Remember that the following statement

 

            int x = 23;

will look like the following in memory.

 

           

Arrays are the same.  However, they are a sequence of variables.  So the statement

 

            int[] age = new int[6];

 

will look like this in memory:

 

           

 

The red numbers shown are the indexes.  Each rectangle is an element.  We will now see how to access the elements.

 

But first, a bit more on indexing.

INDEXING

 

Each value that is stored in an array has an index.

 

In Java, the first element has index 0, the next element has index 1, …

The last element has an index that is equal to the array’s length – 1.

 

EXAMPLE

 

Question:  What are the indexes of an array of size 8?

 

Answer: 0,1,2,3,4,5,6,7

 

INITIALIZING ELEMENTS

 

Like all variables, each array element has to be initialized before being used.

We can initialize an element x by using:

 

arrayName[x] = value;


 

EXAMPLE 1

Create an integer array called even that is of length 5. The first element should get number 2, the next element number 4, the next number 6, and so on…

int[] even = new int[5];

even[0] = 2;

even[1] = 4;

even[2] = 6;

even[3] = 8;

even[4] = 10;

 

EXAMPLE 2


Create a String array called sa of length 4 and store a person’s name in each element.

 

     String[] sa = new String[4];

     sa[0] = “Daniel”;

     sa[1] = “Erik”;

     sa[2] = “Jason”;

     sa[3] = “Milan”;


EXAMPLE – ARRAY IN MEMORY

 

Question:

 

Consider the sa array from Example 2.  How will that look in memory?

 

Solution:

 

           


OUT OF BOUNDS ERROR

 

If one tries to access an element that does not exist, a run-time error occurs. This most commonly occurs when a user tries to access element –1 or an element number that is greater than or equal to the array’s length.

 

EXAMPLE 1 – COMMON ERROR

The following will give an error:

 

     double[] arr = new double[10];

     arr[10] = 33.2;

 

The second statement gives an error because the last element in the array has index number 9.  So there is no element with index 10.

 

EXAMPLE 2 – COMMON ERROR

 

The following will also give an error.

 

     arr[-1] = 42.3;

 

There is no element with index -1 so this will give an error. 

ARRAY LENGTH

 

The length of an array, which is also called the size of an array, is the number of elements in the array.

We can get the length of an array at any time by using:

 

            arrayName.length

 

Note that there are no brackets at the end of length. We will see why this is the case later on.

 

EXAMPLE – ARRAY LENGTH

 

For the sa array used in the example above, we can do the following:

 

          System.out.println(“There are “ + sa.length + “ names in the array.”);

 

And this will output

 

          There are 4 names in the array.

 

PROCESSING ARRAYS USING LOOPS

 

We often need to use loops to process arrays. The for loop is usually the best one to use.

The general template code for a loop that processes an array is:

 

     for (int i = 0; i < arrayName.length; i++)

     {

          //process element i which is arrayName[i]

     }

Example 1

Create a double array of length 200. Use a for loop to initialize each element to 0.0.

 

double[] a = new double[200];

 

for (int i = 0; i < a.length; i++)

{

     a[i] = 0.0;

}

 

Example 2

Consider the code above. Write the statements needed to output the contents of the array to screen.

 

for (int j = 0; j < a.length; j++)

{

     System.out.println(“Element “ + j + “ = “ + a[j]);

}

 


Example 3

Consider the code above. Write the statements needed to calculate the sum of the array elements.


double sum = 0.0;

 

for (int j = 0; j < a.length; j++)

{

     sum = sum + a[j];

}

 

System.out.println(“The sum is “ + sum);

 

JAVA’S STATIC ARRAY SIZE

 

In Java, once an array has been created, its size cannot be changed.

We can of course create a new array of the newly desired length and copy the data into that array. We will look at this more closely later.


RUN-TIME ARRAY SIZE

 

An array size can be decided at execution time.

 

Example

Ask the user for the desired array size and then create an array of that size.

 

           System.out.println(“What array size do you need?”);

           int size = DummiesIO.getInt();

 

           int[] arr = new int[size];

 

           //of course, we would need to do something with this now…

 

SINGLE LINE ARRAY DECLARATION AND INITIALIZATION


We can declare an array and initialize its elements in one step if the array is small enough and predetermined.  This is especially useful when learning about arrays.

See examples below.

 

EXAMPLE

 

Create an array called x that contains the values 0, 4, 6, 2 and 9 in its elements.


            
int[] x = {0, 4, 6, 2, 9};

 

Create an array called yo that contains the first 8 even numbers starting at 2.

 

           int[] y = {2, 4, 6, 8, 10, 12, 14, 16};

 

USEFUL FUNCTION TO GET STRING VERSION OF ARRAY

 

Inside the built-in Arrays class, you will find a function called toString() that will return a String representation of the array.  Because Arrays is not part of the default library, you need to import it using:

 

     import java.util.Arrays;

 

This can be used to output the content of the array to screen without needing a loop.

 

            System.out.println(Arrays.toString(arr));  

 

where arr is the array’s name.