Earlier in the course, we created and used variables that are individual and isolated. For example
int count, sum;
float convertedValue;
String name;
These variables live on their own, and perform useful roles in programs such as holding running totals (gatherers), holding results of calculations (transformations), holding an index into a string being processed (steppers), etc.
Very often however, we deal with data that is not isolated but grouped together in a collection of information. Sometimes the information is in tables. Examples are train timetables, a telephone directory, or bank statements. In programming these are called data structures. The information in a table is related to the other information in the table in some way. One of the simplest types of data structure in programming is the array.
The most basic sort of array, called a one dimensional array, can be considered a table with a single row of information (alternatively you could consider it a table with a single column of information). This could be a table of numbers, a table of strings, or a table of anything else we want. For example an array of numbers:
| 23 | 54 | 96 | 49 | 14 | 29 |
The array above might be used to store the ages of a number of people who live together as a family household.
| John | Paul | George | Pete |
| 0 | 1 | 2 | 3 |
The above table holds the names of members of a band and might be called bandMembers[]. In programming, each item in an array is called an element and we refer to the element by its position in the array, called the index. In the table above the element at index zero is “John”. What element is at index 2? The plural of index is indices – so don’t use the word indexes!
To change an element in an array, you can use it in an assignment statement, for example,
bandMembers[3]="Ringo"; // Replace with new drummer
Square brackets are used in Java and many other programming languages to specify the index of an array element.
1 Dimensional Arrays
There are two steps to create an array in Java:
- you give it a name by giving the data type, followed by square brackets, and then the identifier, e.g. int[] myIntegerArray
- you create the array in memory by using the new keyword, e.g. new int[6], or by initializing it with values.
These lines are usually executed together, like so:
int[] myIntegerArray = new int[6];
You can initialise individual elements like this:
myIntegerArray[1] = 54;
myIntegerArray[5] = 29;
If you want to initialize the array at the same time as declaring it, you can do it with curly brackets.
int[] householdAges = {23,54,96,49,14,29};
You can get the length of an array by using its length property which can be useful in a loop, e.g. householdAges.length will give you 6. (Note there are no brackets after length – because it is an attribute/property of the array object, not a method. Confusingly they are required when dealing with the length of strings, because for a string length() is a method not an attribute).
You could use a loop to initialize all the elements in an array programmatically, e.g:
for (count=0; count<5; count++) myArray[count]=0;
1D Array Activities
Create arrays in Java to do the following:
- Replicate the array above for band members, print out the 4 elements of the array using a for loop.
- Write some code that creates an empty 8 element array, called powersOfTwo. Add a line of code to write 1 to the first element, and then use a loop to write 2,4,8,16,32 and so on into the array (Hint: each value is going to be twice the previous one).
- Write some code that takes in a word from the keyboard and then adds it into the next empty location in a 7 element array. The process repeats until the text “end” is entered or the end of the array is reached.
2 Dimensional Arrays
A 2D array is like a table with multiple rows and columns. You need to use two sets of square brackets to refer to a 2D array, with the first referring to the row, and the 2nd to the column – [R][C]
(Helpful mnemonic, from one of my students: “Row, row, row your Columns, gently down the screen…”)
A 2D array with 3 rows and 6 elements in each row can be initialized as follows:
int[][] myArray = { {1,2,4,6,8,10}, {1,3,6,9,12,15}, {1,4,8,12,16,20} };
You address the 2D array by specifying the row and then column, e.g. myArray[1][5] will give you 15
2D Array Activities
- Create a 2D array of characters. Into each element, place either an ‘o’ or an ‘x’. Use a pair of nested loops to print every row and column in the array.
- One simple way to encrypt a short message is to write it letter by letter into a two-dimensional array. The letters are entered row by row, but read out column by column to give a jumbled version. The message can be decrypted by repeating the process. Write a program that declares an array of characters with five rows and five columns and fills it with ‘space’ characters. It should then input a message, place it letter by letter into the array by rows, then output the result of reading it column by column. The table below shows the contents of the array and the console session below that shows the result if the input message is: “here is my message for ya”.
| h | e | r | e | |
| i | s | m | y | |
| m | e | s | s | |
| a | g | e | f | |
| o | r | y | a |
Message encryption and decryption program
Enter your message (up to 25 characters):
here is my message for ya
hi aoesmgrr ee ems y ysfa
Challenge task: create a separate class in a different file that defines a class called UniversityTown. It will contain attributes but no methods. The three attributes are universityName, studentPopulation, and city.
You can then declare an array of UniversityTown objects in your main method. (In non-object oriented languages like Pascal and C, this type of data structure which can contain attributes of different types is called a record or structure).
After creating the empty array, you have to create each object by using new and should store them into the relevant position in the array.
You program should ask for the name of a city, the name of a unversity in that city, and the number of students in that city. It should repeatedly ask for that information, adding new universities each time until the university name “exit” is entered.
The second part of the program should ask for the name of a city, and then should display the name of universities in that city along with the number of students in that city.
Enter the name of the university or exit to end:
Abertay
Enter the city:
Dundee
Enter the student population of the city:
20000
Enter the name of the university or exit to end:
exit
Enter the name of a city to search for:
Dundee
Universities in Dundee,
Abertay
Dundee University
Student population:
20000
3D Arrays
It is possible to have arrays with more dimensions – at A Level you will be expected to be familiar with 3D arrays and not beyond. The process is an extension of the 2D syntax, e.g:
int[][][] my3Darray = { { {1,2,3},{4,5,6},{7,8,9} },
{ {21,22,23},{24,25,26},{27,28,29} },
{ {31,32,33},{34,35,36},{37,38,39}}};
You can think of the additional dimension as a layer in a 3D cube, so extending our 2D table of row and column, you now have a layer, row and column:
System.out.println(my3Darray[2][2][2]); //prints 39 to screen
Create a simple 3D array, and experiment with printing and changing values so you get an understanding of how they work.
Knowledge Check
- What is the formal name of an individual item in an array?
- What is the formal name of the position of an item in an array?
- What is the plural name of positions of items in arrays?
- What two steps are there when creating an array in Java?
- What error would the following code cause?
- int[] myArray = new int[1000];
- System.out.println(myArray[1000]);
- Think of a scenario in a program where it might be useful to store items, e.g. integers, in an array.