thecodex.expert · The Codex Family of Knowledge
Java

Methods

There is no such thing as a free-standing function in Java — every single method, without exception, lives inside a class.

Java 21 LTS Overloading resolved at compile time Last verified:
Canonical Definition

A method declares an access modifier, return type, name, and parameter list, and must be defined inside a class (or interface) — Java has no top-level functions the way Python or Go does. Method overloading allows multiple methods sharing a name but differing in their parameter types or count; the compiler picks which overload to call based on the argument types at each call site, resolved entirely at compile time.

Method basics: access, return type, parameters

void indicates the method returns nothing; any other type must be returned by every code path, or the compiler rejects it.

JavaCalculator.java
public class Calculator {
    public int add(int a, int b) {
        return a + b;
    }

    public void printResult(int result) {   // void: no return value
        System.out.println("Result: " + result);
    }
}

Overloading: same name, different signatures

The compiler decides which overload to call by matching the argument types against each declared signature — this happens entirely at compile time, unlike runtime polymorphism through inheritance.

JavaOverloading.java
public class MathUtils {
    public int add(int a, int b) {
        return a + b;
    }

    public double add(double a, double b) {   // overload: different parameter types
        return a + b;
    }

    public int add(int a, int b, int c) {      // overload: different parameter count
        return a + b + c;
    }
}

MathUtils m = new MathUtils();
m.add(1, 2);         // calls the (int, int) version
m.add(1.5, 2.5);      // calls the (double, double) version
m.add(1, 2, 3);        // calls the (int, int, int) version

Varargs: a variable number of arguments

The ... syntax lets a method accept any number of arguments of that type, treated inside the method body as a regular array — a method can only have one varargs parameter, and it must be the last one.

JavaVarargs.java
public int sum(int... numbers) {   // varargs
    int total = 0;
    for (int n : numbers) {
        total += n;
    }
    return total;
}

sum();              // 0 — zero arguments is fine
sum(1, 2, 3);        // 6
sum(1, 2, 3, 4, 5); // 15

Sources

1
Oracle. The Java Tutorials, "Defining Methods" and "Arbitrary Number of Arguments," docs.oracle.com/javase/tutorial.