What will you build

You will build a small application that will use a one dimension array, and a multi-dimension array.

In this codelabs, you will need to use the class Student that you have created in the codelabs How to implement a constructor.

What You'll Learn

What will you need

An array is a data structure consisting of a set of related data items of the same type referred to as elements of the array. The values that are stored in an array are called its "elements".

To declare an array, define the variable type with square bracket.

Comment: You declare an array of String when you implement the main method, as the parameter of the main is always a array of type String.

Some example of declaration of array. The first one will be a array of type String. The second one will be an array of type int, and the third one will be an array of type Student.

String[] names;
int[] numbers;
Student[] students;

You have several way of insantialise and initialise an array. One was is to use the keyword new, as for any object in Java. The second way is to instialise and initialise with values. The length of an array is fix and need to be declared when the array is instantialised.

String [] names = new String [10] // instantialisation and initialisation of an array of String of length 10.
int [] numbers = {1,10,3} // instantialisation and initialisation of an array of int with the values already given, the lenght of this array is 3, as this is the number of elements
Student [] students = new Student [3] // instantialisation and initialisation of an array of type Student of length 3.

The array names and students will be initialised with null (if it was an int or double with 0 and a boolean with false).

To access the value in an array, again several possibilities (we will see the other one next page). Each element in an array is specified by an integer index. The index number needs to be specified inside the square bracket.

int n = numbers[1]

The number that will be stored in "n" will be 10, as it is at the second position of the array numbers. Array index start at 0.

To store an element in an array several methods exists but for all of them, the index need to be specified. The next code will store an instance of the class Student at the index position 0.

students[0] = new Student("Helene","Cardiff university");

The next line will store an String in the array names at the index 1.

names[1] = "helene";

java documentation for array

To access the value stored in an array, we can use a loop to iterate through the array.

To know the size (length) of an array, you need to use the built-in length property. If you don't use it, and you loop through you array but go further that the size of the array, the compiler will raise an error : Array index out of bounds exception.

public class DemoArray {

    public void displayArray(){
        String [] names = {"helene","Alexia","Ian"};
        for (int i = 0; i < names.length; i++){
            System.out.println("names "+names[i]);
        }
    }

    public static void main (String[] args){
        DemoArray da = new DemoArray();
        da.displayArray();
    }
}

To access the value stored in an array, we can use a loop to iterate through the array.

The little application that we will build to understand the array is an application that will use the class Student we defined in the codelab How to implement a constructor.

We will implements a class "Classroom" that will contains several students. The constructor of the class Classroom take an argument of type array of Student. We will implement a method that will loop through the array of Student to display the name of the student. This method will call the method returnNameStudent from the class Student.

public class Classroom{

    private Student[] students;

    public Classroom(Student[] students){
        this.students = students;
    }

    public void displayStudents(){
        for (int i = 0; i < students.length; i++){
            System.out.println(students[i].returnNameStudent());
        }
    }
}

As usual you will create a class to test this class. We will need to use the two class: Student and Classroom in this class.

We will need to declare some instance of object of type Student (as many as you want, in the following example, I declared 4 instance of the class Student) and store them in an array of type Student. I used two different way to create these instances of Student. One is declaring a variable of type Student, instantiate and initialise the Student with the different values and store it in the declared variable. The second way is to instantiate and initialise the variable straight in the initialisation of the array it-self (Ian).

We will pass this array of student to the constructor of the class Classroom to instantialise an array of the type Student.

From the instance of the Classroom, I am invoking the method displayStudent.

public class Main {

    public static void main(String[] args) {
	Student helene = new Student("Helene", "Cardiff university");
	Student anne = new Student ("Anne", "Cardiff university");
	Student james = new Student ("James", "Cardiff university");
	Student[] students = {helene,anne,james, new Student("Ian","Cardiff University")};
	Classroom classSDS1 = new Classroom(students);
	classSDS1.displayStudents();

    }
}

As a reminder there is the class Student:

public class Student{

    String nameStudent;
    String nameUniversity;

    public Student(String nameStudent, String nameUniversity){
        this.nameStudent = nameStudent;
        this.nameUniversity = nameUniversity;
    }
    public Student(){
        this("Helene","Cardiff university");
    }

    public String returnUniversityName(){
        return nameUniversity;
    }

    public String returnNameStudent(){
        return nameStudent;
    }
}

In the same way we used a for loop to display the elements of an array, we can use a for loop to store elements in an array.

In this small application, we will store numbers in an array and calculate the average of these numbers.

public class CalculateAverage{

    public double calculateAverage(int numberOfNumbers){
    	
    	//declare, instantialise and initialise an array of double. 
    	//The size is given by the parameter of the method.
        
        double[] numbers = new double[numberOfNumbers]; 
        
        for (int i = 0; i < numberOfNumbers; i++ ) {
            numbers[i]=i+1;//storing the value of i, in the array numbers
        }
        double total = 0;
        for (int j = 0; j < numbers.length;j++){//looping through the array again
            total = numbers[j]+total; //storing the value of element of the array in total and adding it
        }
        return total/numbers.length; //divide the total of all numbers by the lenght of the array
    }

    public static void main (String[] args) {
        CalculateAverage ca = new CalculateAverage();
        System.out.println(ca.calculateAverage(4));
    }

}

You saw in the How to iterate codelabs how to iterate. However, since Java version 5.0, a shortcut as been implemented to iterate through a collection: the for each. If you need to iterate through a sequence of elements, this is a very convenient way of doing it.

However, it doesn't allow to access to the index, and by consequence is not suitable for all algorithm that need to be implemented. The for each, will not be suitable, for example, to modify an element of the array, or to access directly to one element of the array.

The aim of the for each loop is to get the elements of a collection from the beginning to the end.

For this example, we will use again the Student class and the student Classroom and we will only add a method to the Classroom class.

public class Classroom{

    private Student[] students;

    public Classroom(Student[] students){
        this.students = students;
    }

    public void displayStudents(){
        for (int i = 0; i < students.length; i++){
            System.out.println(students[i].returnNameStudent());
        }
    }
    
    public void displayStudentsForEach(){
    	for (Student s: students){
    		System.out.println(s.returnNameStudent());
    	}
    }
}

As you can notice, the difference between the "for each" and the ordinary loop. In the "for each" loop, you defined in the declaration of the loop the type of variable that is contains in the collection.

In the above exemple, the collection contains elements of type Student. After the declaration of the type of variable you want to loop through, you declare a name for the variable.

This variable is only defined inside the loop.

After the declaration of the variable, it is followed by a colon. Followed by the collections you want to iterate through. In the example above, we are iterating through the students array.

An array can be multi-dimensional. You can defined as many dimension that you want.

A two dimensional array can be thought as a table of rows and columns, however, it is a little bit different, as it can be not necessarily symmetrical.

To searching a multi-dimensional array, it is common to use a nested loop.

public class MultiDimensionDemo {

    public int[][] multi;

    public MultiDimensionDemo() {
        this.multi = new int[][] {{1,6,6},{2,10,10,22}};
    }
    public int[][] getmulti(){
        return this.multi;
    }
    public void displayMulti(){
        int[][] m =this.getmulti();
        for (int i=0; i<m.length; i++) {
            for (int j =0; j<m[i].length; j++) {
                System.out.print(" "+m[i][j]);
            }
            System.out.println(" ");
        }
    }

    public static void main(String args[]){
        MultiDimensionDemo multi = new MultiDimensionDemo();
        multi.displayMulti();

    }
}

The array is the simplest data structure to store a collection of object or primitive. However, arrays have a really annoying issue. They cannot grow or shrink, and adding or removing data from them are difficult.

This example will show how to increase the size of an array. Imagining that you have an array of 10 integers, and you would like to add some number in it. The only way of doing this, is to copy the value already existing in an array and add the new integers you would like to store.

public Student[] copyArrayStudents(Student[] arrayStudent) {
    int lenghtArray = arrayStudent.length;
    Student[] studentsDestination = new Student[lenghtArray + 1];
    System.out.println(studentsDestination.length);
    System.arraycopy(arrayStudent, 0, studentsDestination, 0, lenghtArray);
    studentsDestination[studentsDestination.length-1] = new Student("Carl", "Cardiff University");
    return studentsDestination;
    }

The class to test the method.

public class Main {

    public static void main(String[] args) {
	Student helene = new Student("Helene", "Cardiff university");
	Student anne = new Student ("Anne", "Cardiff university");
	Student james = new Student ("James", "Cardiff university");
	Student[] students = {helene,anne,james, new Student("Ian","Cardiff University")};
	Classroom classSDS1 = new Classroom(students);
	classSDS1.displayStudents();
	Student[] studentsDestination = classSDS1.copyArrayStudents(students);
	for (Student s : studentsDestination) {
			System.out.println(s.returnNameStudent());
		}
    }
}

The documentation for the System.arraycopy()

However, array is still very useful, and you have several methods proposed for this data structure.

You can find the code for this example in https://git.cardiff.ac.uk/ASE_GROUP_2020/code_for_codelabs.git