Version without JavaScript, read-only: workshops, quizzes and running code are not available here. Full version · Catalogue · Sign in

Lecture notes · chapter 9

Arrays

Declaration, length, indices and arrays of arrays.

9.1 Definition

An array is introduced by the syntax [], placed after the type of the elements. Its size is obtained with the attribute length.

int[] monTableau = { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 };
int taille = monTableau.length;
int premierElement = monTableau[0];

// Advanced syntax
int[] tb;
int[] tb2 = new int[10];
int[] tb3 = new int[5], tb4 = new int[10];
String[] strValues = new String[5];
String[] noms = { "toto", "titi", "tata" };

Traversal and overflow

public class Demo {
    public static void main(String[] args) {
        int[] notes = { 12, 15, 8, 19 };
        System.out.println("size: " + notes.length);

        for (int i = 0; i < notes.length; i++) {
            System.out.println("notes[" + i + "] = " + notes[i]);
        }

        // for-each loop: when the index is not needed
        int somme = 0;
        for (int note : notes) {
            somme += note;
        }
        System.out.println("sum: " + somme);

        // Uncomment to see the exception:
        // System.out.println(notes[4]);
    }
}

9.2 Multi-dimensional arrays

An array can have several dimensions: from Java's point of view, it is an array of arrays.

A 3×5 matrix filled from 0 to 14

public class Demo {
    public static void main(String[] args) {
        int[][] matrice = new int[3][5];

        int k = 0;
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 5; j++) {
                matrice[i][j] = k++;
            }
        }

        for (int i = 0; i < matrice.length; i++) {
            for (int j = 0; j < matrice[i].length; j++) {
                System.out.print(matrice[i][j] + "\t");
            }
            System.out.println();
        }
    }
}