AnyCompiler

Methods

A method lives inside a class and has a return type, a name, and a list of parameters. static methods like the ones in this lesson belong to the class itself rather than to any particular instance, which is why main() — itself static — can call them directly.

public class Main {
    static int add(int a, int b) {
        return a + b;
    }

    public static void main(String[] args) {
        System.out.println(add(3, 4));
    }
}
Output
7

Method overloading

Java lets you declare multiple methods with the same name as long as their parameter types differ — this is overloading. The compiler picks the right one at compile time based on the argument types at the call site, with no runtime cost involved.

public class Main {
    static int add(int a, int b) {
        return a + b;
    }

    static double add(double a, double b) {
        return a + b;
    }

    public static void main(String[] args) {
        System.out.println(add(3, 4));
        System.out.println(add(3.5, 2.5));
    }
}
Output
7
6.0

Next: arrays and ArrayList — Java's fixed-size arrays versus the growable ArrayList collection.

Practice exercise

Write a method multiply(int a, int b) that returns a * b, then print multiply(6, 7).