Methods

Introduction

As programs grow, the same steps are needed in several places, and long main methods become hard to follow. Methods give a piece of work a name, take the data it needs as parameters and hand back a result. Java checks every call against the method's declaration, so passing text where a number is expected, or forgetting to return a value, is caught before the program runs.

How it works

A method declaration states who may call it, whether it belongs to the class, its return type, its name and its parameters:

static int square(int x) {
    return x * x;
}

static means the method belongs to the class itself, so main, which is also static, can call it directly as square(7). Methods that belong to objects come with classes, later in the course. The return type says what the method gives back; void means nothing. A non-void method must return a value on every path, or javac reports "missing return statement".

Overloading lets several methods share a name if their parameter lists differ: average(int, int) and average(int, int, int) are two methods, and javac picks the one whose parameters match the call. The return type alone cannot tell overloads apart.

A recursive method calls itself on a smaller version of the problem. It needs a base case that stops the recursion, otherwise the calls go on until the stack runs out with a StackOverflowError. Factorial is the classic example: factorial(n) is n * factorial(n - 1), and factorial(1) is 1.

Java is always pass-by-value: each argument is copied into the parameter. Assigning a new value to a parameter changes only the copy. With objects such as arrays, the value copied is a reference to the object, so a method can change the object's contents, which the caller sees, but cannot make the caller's variable point at a different object.

Variables declared inside a method are local: they exist only while it runs, and each call, including each recursive call, gets its own.

Example

// Static methods: parameters, return values, overloading, recursion and pass-by-value.
public class Main {
    static int square(int x) {
        return x * x;
    }

    static double average(int a, int b) {
        return (a + b) / 2.0;
    }

    static double average(int a, int b, int c) { // an overload: same name, other parameters
        return (a + b + c) / 3.0;
    }

    static long factorial(int n) {
        if (n <= 1) return 1;
        return n * factorial(n - 1); // the method calls itself
    }

    static void tryToChange(int value) {
        value = 99; // changes only the method's own copy
    }

    public static void main(String[] args) {
        System.out.println(square(7) + " " + average(3, 4) + " " + average(3, 4, 8));
        System.out.println(factorial(5) + " " + factorial(20));
        int x = 5;
        tryToChange(x);
        System.out.println(x);
    }
}
Open in compiler

Line by line

  1. square takes an int and returns an int.
  2. The two average methods are overloads; one divides by 2.0 and the other by 3.0, so both return doubles.
  3. factorial stops at its base case and otherwise calls itself with n - 1; it returns a long because 20! is too big for an int.
  4. tryToChange assigns to its own copy, so x in main is still 5.

Expected result

49 3.5 5.0
120 2432902008176640000
5

In the real world

Professional Java code is made of many short methods, each with a clear name and a few parameters; code reviews often ask for a long method to be split. The Java standard library is itself thousands of methods, such as Math.max and String.valueOf, many of them overloaded for each type. Recursion is the natural way to walk trees, such as folders on a disk or the structure of a web page.

Common mistakes

  • Forgetting to return a value on one path of a non-void method.
  • Recursion without a base case, ending in a StackOverflowError.
  • Expecting a method to change an int argument in the caller.
  • Calling an instance method from static main without an object, which javac rejects.

Best practices

  • Give methods verb names that say what they do: computeTotal, isValid.
  • Keep each method short and focused on one task.
  • Prefer returning a result to printing inside the method, so the result can be reused and tested.

Summary

Methods name a piece of work, with typed parameters and a return type that javac checks at every call. Overloads share a name with different parameters, recursion solves a problem through smaller copies of itself down to a base case, and Java passes every argument by value.

Quick check

1. What does a void method return?
2. Which pair are valid overloads?
3. What happens to a recursive method with no base case?
4. A method sets its int parameter to 99. What happens to the caller's variable?

Key takeaways

  • A method declares its return type and its parameter types; javac checks every call.
  • Overloads share a name but differ in their parameters; javac picks the one that fits.
  • Arguments are copied: a method cannot change the caller's variables, though it can change an object both can reach.

Practice problems for this lesson

My notes

Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.