Skip to content
Educora
Beginner16 min6 / 18

Methods

Split code into reusable methods: parameters, return values, void, static, overloading and recursion.

Check yourself
In this lesson you will learn
  • Write and call a static method with parameters and a return value
  • Use method overloading
  • Explain that Java passes arguments by value

Imagine you have to calculate the area of a room in ten places in your program. If you write the same formula ten times, fixing one mistake means changing ten places. A method is a named block of code: you write it once and call it as often as you like. You already know one method — main.

The structure of a method

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

    static double area(double width, double height) {
        return width * height;
    }

    static boolean isEven(int n) {
        return n % 2 == 0;
    }

    public static void main(String[] args) {
        greet("Aysel");
        greet("Murad");
        double room = area(4.5, 3);
        System.out.println("Room area: " + room);
        System.out.println(isEven(10) + " " + isEven(7));
    }
}
Expected output
Hello, Aysel!
Hello, Murad!
Room area: 13.5
true false
  • static means the method belongs to the class and can be called without creating an object. You will meet object methods in the next module.
  • The return type (void, double, boolean) says what the method gives back. void means “returns nothing”.
  • The parameters in the parentheses are the method's input; each has a type and a name. The actual values passed in a call are called arguments.
  • return sends the result back to where the method was called and ends the method immediately.

Notice that in the call area(4.5, 3) the 3 is an integer, but the parameter is a double — Java widens it to 3.0 automatically. Methods that return a boolean usually have names starting with is or has: isEven, hasTicket.

Overloading and the Math class

Java allows several methods with the same name — as long as their parameter lists differ (in number or types). This is called method overloading. The compiler picks the right version by looking at the arguments. A different return type alone is not enough.

Java
public class Main {
    static int max(int a, int b) {
        return a > b ? a : b;
    }

    static double max(double a, double b) {
        return a > b ? a : b;
    }

    static int max(int a, int b, int c) {
        return max(max(a, b), c);
    }

    public static void main(String[] args) {
        System.out.println(max(3, 9));
        System.out.println(max(2.5, 1.5));
        System.out.println(max(4, 11, 7));
        System.out.println(Math.max(5, 8) + " " + Math.sqrt(49) + " " + Math.pow(2, 10) + " " + Math.abs(-3));
    }
}
Expected output
9
2.5
11
8 7.0 1024.0 3

Arguments are passed by value

When a method is called, Java copies the value of each argument into the parameter. So changing an int parameter inside the method does not affect the caller's variable. With arrays and objects, however, what gets copied is not the object itself but a reference to it — through that reference the method can change the elements of the very same array.

Java
public class Main {
    static void tryToChange(int x, int[] arr) {
        x = 100;
        arr[0] = 100;
    }

    public static void main(String[] args) {
        int number = 1;
        int[] numbers = {1, 2, 3};
        tryToChange(number, numbers);
        System.out.println(number);
        System.out.println(numbers[0]);
    }
}
Expected output
1
100

Recursion and variable arguments

A method can also call itself — this is called recursion. Every recursive method needs a stopping condition, otherwise the calls go on forever and the program stops with a StackOverflowError. The notation int... values lets you pass any number of arguments to a method; inside the method they look like an array.

Java
public class Main {
    static int factorial(int n) {
        if (n <= 1) {
            return 1;
        }
        return n * factorial(n - 1);
    }

    static int sum(int... values) {
        int total = 0;
        for (int v : values) {
            total += v;
        }
        return total;
    }

    public static void main(String[] args) {
        System.out.println(factorial(5));
        System.out.println(sum(1, 2, 3));
        System.out.println(sum(10, 20, 30, 40));
        System.out.println(sum());
    }
}
Expected output
120
6
100
0
How is factorial(5) calculated?

Trace the call factorial(5) of the recursive factorial method step by step.

Show solution
factorial(5) = 5 · factorial(4)
factorial(4) = 4 · factorial(3)
factorial(3) = 3 · factorial(2)
factorial(2) = 2 · factorial(1)
factorial(1) = 1 — the stopping condition.
Now we go back up: 2 · 1 = 2, 3 · 2 = 6, 4 · 6 = 24, 5 · 24 = 120.

Key points

  • A method is a named block of code: written once, called many times.
  • The header gives the return type, name and parameters; void returns nothing, other types require return.
  • Overloading: methods with the same name must have different parameter lists.
  • Java passes arguments by value; for arrays and objects the value copied is a reference.
  • A recursive method must always have a stopping condition.

Check yourself

10 questions. Every correct answer earns XP.

1 / 10
What does the return type void mean?