Skip to content
KALANBLON
Show contents

Chapter 1 of 7 · 20 min

Writing your own methods

By the end of this chapter, you'll be able to

  • Define a method with parameters and a return value
  • Tell a method that returns a value from a void method
  • Use overloading to offer several versions of a method
  • Explain what a method can change when you pass it an object

Defining and calling a method

double average(int[] grades) {
    if (grades.length == 0) {
        return 0;
    }
    int sum = 0;
    for (int g : grades) {
        sum += g;
    }
    return (double) sum / grades.length;
}

void showReport(String className, int[] grades) {
    IO.println(className + ": " + average(grades));
}

void main() {
    showReport("Class 10A", new int[] {12, 15, 9, 14});
    showReport("Class 10B", new int[] {});
}
Class 10A: 12.5
Class 10B: 0.0
  • The return type comes before the name: double average(...) returns a double, void showReport(...) returns nothing.
  • The parameters are typed; when calling, the arguments are matched with them in order.
  • return sends back the result and ends the method. The first return here handles a special case (no grades) before the general case.
  • A method can call another one. The order of definition doesn't matter in Java: main can be written at the end or at the beginning.
  • By convention, method names start with a lowercase letter and follow camelCase: showReport, computeTotal.

We display 60.

Step 6 of 6
Text description of the animation
  1. A method computes a price after a discount.
  2. To compute total, Java first has to call discount.
  3. The method has its own memory: the parameters receive copies of the arguments.
  4. The calculation gives 60: return sends it back and the method ends.
  5. Back in main, the returned value is stored in total. The parameters have disappeared.
  6. We display 60.

Overloading

Several methods can have the same name if their parameters differ. Java picks the right version from the arguments:

String formatPrice(double amount) {
    return formatPrice(amount, "€");
}

String formatPrice(double amount, String currency) {
    return String.format("%.2f %s", amount, currency);
}

void main() {
    IO.println(formatPrice(19.9));
    IO.println(formatPrice(4500, "XOF"));
}
19.90 €
4500.00 XOF

The short version calls the full version with a default value: the logic is only written once. (Java has no default parameters; this is the usual way to replace them.)

What a method can change

In Java, arguments are always copied. But for an object (a list, an array, an instance of a class), what's copied is the reference, that is, the means of reaching the object. So the method reaches the same object as the caller:

  • it can change its contents (add to a list, change a box of an array), and the caller will see the change;
  • but if it replaces its parameter with another object, the caller won't know about it.

Your turn

Worked exercise

Worked exercise: the password toolbox

Write two methods: boolean isStrong(String password), which returns true if the password is at least 12 characters long and contains at least one digit, and int strongCount(List<String> passwords), which counts the strong passwords in a list by reusing the first one. With the list "sunshine", "Morning-sun-7-tea", "123456789012" and "long-password-here", the program must display 2 strong out of 4.

Hint 1
password.length() gives the length, and Character.isDigit(c) tests whether a character is a digit. Go through the characters with for (char c : password.toCharArray()).
Hint 2
In isStrong, return false straight away if the password is too short: the rest of the code is simpler.
Show the solution and common mistakes
boolean isStrong(String password) {
    if (password.length() < 12) {
        return false;
    }
    for (char c : password.toCharArray()) {
        if (Character.isDigit(c)) {
            return true;
        }
    }
    return false;
}

int strongCount(List<String> passwords) {
    int n = 0;
    for (String p : passwords) {
        if (isStrong(p)) {
            n++;
        }
    }
    return n;
}

void main() {
    var passwords = List.of("sunshine", "Morning-sun-7-tea", "123456789012", "long-password-here");
    IO.println(strongCount(passwords) + " strong out of " + passwords.size());
}
2 strong out of 4

These two criteria are deliberately simple. In practice, length matters much more than the variety of characters, and a password manager remains the best solution.

Common mistakes:

  • Putting return false; inside the loop, in an else: the method would stop at the first character that isn't a digit.
  • Copying the tests of isStrong into strongCount instead of calling it: you're back to the problem of copies you forget to fix.

Summary

  1. 1A method has a return type (or void), a camelCase name and typed parameters.
  2. 2return sends back a value and ends the method.
  3. 3Overloading allows several methods with the same name and different parameters.
  4. 4Arguments are copied; for an object, it's the reference that's copied.
  5. 5A method can change the contents of an object it receives, but not replace the caller's object.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.