Methods

Return type, name, parameters, body:

int add(int a, int b) {
    return a + b;
}

void greet(String name) {          // void = returns nothing
    IO.println("Hello, " + name);
}

Arguments are copies

Java is always pass-by-value. For objects the reference is copied — you can mutate the object, but not reassign the caller’s variable.

void fill(List<String> list) {
    list.add("new");            // visible to the caller
    list = new ArrayList<>();   // local only
}

Overloading

Same name, different parameter lists:

int area(int side)                { return side * side; }
int area(int width, int height)   { return width * height; }
double area(double radius)        { return Math.PI * radius * radius; }

A different return type alone is not enough.

Varargs

int sum(int... numbers) {
    var total = 0;
    for (var n : numbers) total += n;
    return total;
}

sum();            // 0
sum(1, 2, 3);     // 6

Must be the last parameter.

Scope

A variable lives inside its block:

void demo() {
    var outer = 1;
    if (outer > 0) {
        var inner = 2;
    }
    IO.println(inner);   // error: does not exist here
}

static methods belong to the class, not an instance:

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

MathHelper.square(5);

Writing good methods

  • one job per method, and the name says it — if you need “and”, split it
  • verbs first: computeDiscount, loadCustomer, isValid
  • more than three parameters? use a record instead
  • return early instead of nesting
String grade(int points) {
    if (points < 0 || points > 100) return "invalid";
    return points >= 50 ? "pass" : "fail";
}

Recursion

long factorial(int n) {
    if (n <= 1) return 1;        // base case
    return n * factorial(n - 1);
}

Java has no tail-call optimisation — deep recursion throws StackOverflowError.

★ Exercises

  1. isPalindrome(String) — ignore case.
  2. Overload max three ways: two int, two double, any number of int.
  3. countVowels(String).
  4. Write Fibonacci recursively and iteratively; time both for n = 40 with System.nanoTime().
  5. formatName(String first, String last)"Miller, Ann", tolerating stray spaces and mixed case.