Skip to content
Theory · Methods · lesson 1 of 8

Your own methods

What you'll learn

What you'll learn:

  • write your own methods with parameters and return and call them from main;
  • explain why a method cannot change a variable you pass to it;
  • predict which of several methods with one name the compiler picks;
  • trace a recursive method through the call stack.

Picture a blender in the kitchen. You put food into the jar, press the button and get a smoothie. To make another one, nobody builds a new blender: you put other food into the jar and press the button again.

In a program, a method plays the part of that appliance. You already write one method in every program, main. But you can add your own methods to the class as well.

Why? If a program needs the same calculation five times, without a method you would write it five times. A bug in it would then have to be fixed in five places.

A method is written once and called as often as you like. Here is a method that squares a number:

JAVA
public class Main {
    static int square(int x) {
        return x * x;
    }

    public static void main(String[] args) {
        System.out.println(square(3)); // 9
        System.out.println(square(5)); // 25
        int total = square(2) + square(4);
        System.out.println(total);     // 20
    }
}

Let's walk through the program step by step:

  1. The method square is declared inside the class Main, next to main, not inside it.
  2. As always, the program starts in main. square(3) is a call: main hands the number 3 to the method and waits for the answer.
  3. Inside square the variable x is 3, and return x * x; returns 9.
  4. The 9 takes the place of the call square(3), and println prints it.
  5. The call square(5) works the same way and gives 25.
  6. In the line int total = square(2) + square(4); the two calls give 4 and 16, so total gets 20.

The method header

The first line of the method, static int square(int x), is its header. It says how to call the method and what it returns. Let's read it from left to right:

  • static, as on main: the method belongs to the class Main itself, so main calls it by name: square(3);
  • int is the result type: the method returns a whole number;
  • square is the method's name; it is written like a variable name, starting with a lowercase letter: square, findMax;
  • (int x) is a parameter: a variable of the method that gets a value when the method is called.

After the header comes the method's body in curly braces: the statements that run on every call.

Parameters and arguments are often mixed up, and interviewers tell them apart:

  • a parameter is the variable in the header: x in square(int x);
  • an argument is the value passed in a call: 3 in square(3).

A method can take several parameters, separated by commas: static int max(int a, int b). A call then passes as many arguments, in the same order: max(3, 7).

The order of methods in a class does not matter: square could also be written below main. A method does not run where it is written; it runs when it is called.

Here the blender picture is off. You can switch a blender on with an empty jar, but you cannot call a method that has a parameter without an argument: for square() the compiler answers method square in class Main cannot be applied to given types.

The return statement

The return statement does two things:

  1. it hands a value back to the place of the call;
  2. it ends the method at once: the lines after it do not run.

The value after return must fit the result type: a method of type int cannot return the string "hi".

The compiler checks return strictly. A method with a result type must return a value on every path through it. The check happens before the program runs, so it does not matter which arguments the method is actually called with. The compiler does not evaluate conditions, so to it an if without a final else always has a path around it, even when your conditions cover every number.

void methods

Not every method calculates something. Sometimes it only performs an action, such as printing. Then you write void in place of the result type, as on main:

JAVA
public class Main {
    static void greet(String name) {
        System.out.println("Hi, " + name);
    }

    public static void main(String[] args) {
        greet("Anna"); // Hi, Anna
        greet("Bob");  // Hi, Bob
    }
}

What matters about void methods:

  • they never contain return with a value, and return; with no value ends the method early;
  • a call to such a method stands as a statement of its own: int n = greet("Anna"); does not compile, because the call has no value.

Variables inside a method

A method's parameters and the variables declared in its body are local. They appear when the method is called and disappear when it finishes. Other methods cannot see them:

  • main cannot read x from square: the compiler answers cannot find symbol;
  • square does not see the variables of main;
  • so two methods can each have a variable with the same name, and these are two different variables.

A blender does not know what is in your fridge either: it works only with what was put into the jar.

Common mistake

The method returns a value on some paths only:

JAVA
static int abs(int x) {
    if (x < 0) {
        return -x;
    }
} // ✗
TEXT
error: missing return statement

The program does not compile. When x is not negative, the method reaches its closing brace without meeting a return. The compiler checks every path, not only the one your call takes, so the error appears even if you only ever call abs(-5). Add return x; before the method's closing brace.

Key points

  • A method is declared in the class next to main: static, the result type, the name, the parameters and the body — static int square(int x) { return x * x; }.
  • A call puts the arguments into the parameters, and return hands a value back to the place of the call and ends the method.
  • A method with a result type must return a value on every path, or the program does not compile: missing return statement.
  • A void method returns nothing; a method's parameters and variables are visible only inside it.