Lesson 13 / 38

Methods

Declare methods with typed parameters and return values, learn pass-by-value semantics, and use overloading and varargs for flexible APIs.

Declaring a method

A method has a return type (void if none), a name, and typed parameters. Arguments are passed by value — for objects, the value passed is the reference.

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

static void greet(String name) {
    System.out.println("Hi " + name);
}

Overloading & varargs

Several methods can share a name if their parameter lists differ (overloading). int... nums accepts any number of arguments as an array.

static int sum(int... nums) {
    int t = 0;
    for (int n : nums) t += n;
    return t;
}
sum(1, 2, 3);       // 6
sum();              // 0