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

Lecture notes · chapter 7

Functions

Declaration, prototype, return, overloading and variadic arguments.

7.1 Definition

A recursive function is made of two elements:

  • a base case (AB-SO-LUTE-LY ESSENTIAL!);
  • a recursive call that moves towards the base case.

7.2 Declaration

static type_de_donnee nomDeLaFonction(type1 argument1, type2 argument2, ...) {
    // list of instructions
}
  1. type_de_donnee is the type of value the function is supposed to return (char, int, float…).
  2. If the function returns no value, it is preceded by the keyword void.
  3. A function must always have a return type.
  4. The same naming rules apply as for variables.
  5. Arguments are optional, but the parentheses remain mandatory.

The definition line is called the prototype.

7.5 Returning a value

A function can return a value (and therefore end) with the keyword return.

7.6 Function overloading

Four somme functions, a single name

public class Demo {
    public static void main(String[] args) {
        System.out.println(somme(1, 2));
        System.out.println(somme(1.5f, 2.5f));
        System.out.println(somme(1f, 2f, 3f));
        System.out.println(somme(1.9f, 2));
    }

    static int somme(int p1, int p2) {
        return p1 + p2;
    }

    static float somme(float p1, float p2) {
        return p1 + p2;
    }

    static float somme(float p1, float p2, float p3) {
        return p1 + p2 + p3;
    }

    static int somme(float p1, int p2) {
        return (int) p1 + p2;
    }
}

7.7 Variadic arguments

Varargs allow a function to receive a variable number of arguments of the same type, without explicitly declaring an array. You write the type followed by three dots ...; inside the function, it is an array.

Varargs, alone then combined

public class Demo {
    public static void main(String[] args) {
        maMethode(1, 2, 3);
        maMethode(10, 20, 30, 40);
        avecPrefixe("value = ", 7, 8);
        System.out.println("total: " + total(1, 2, 3, 4));
    }

    public static void maMethode(int... nombres) {
        for (int nombre : nombres) {
            System.out.println(nombre);
        }
    }

    public static void avecPrefixe(String prefixe, int... nombres) {
        for (int nombre : nombres) {
            System.out.println(prefixe + nombre);
        }
    }

    public static int total(int... nombres) {
        int somme = 0;
        for (int nombre : nombres) {
            somme += nombre;
        }
        return somme;
    }
}