V
Vel·ToolKit
Simple · Fast · Ready to use
EN
Chapter 5 of 20

Methods

Signatures, overloading, varargs, static, method references

Method Definition

Format: [modifiers] returnType methodName(parameterList) { body }. A void return type means no value is returned.

// Methods.java
public class Methods {
    // a static method can be called directly via the class name
    static int add(int a, int b) {
        return a + b;
    }

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

    public static void main(String[] args) {
        System.out.println(add(2, 3));
        greet("Alice");
    }
}

Overloading

Within one class, methods with the same name but different parameter lists (count / type / order); the compiler picks the best-matching version by the argument types at the call site. The return type does not participate in overload resolution.

// Overload.java
public class Overload {
    static int sum(int a, int b) { return a + b; }
    static double sum(double a, double b) { return a + b; }
    static int sum(int a, int b, int c) { return a + b + c; }

    public static void main(String[] args) {
        System.out.println(sum(1, 2));         // calls the first
        System.out.println(sum(1.5, 2.5));     // calls the second
        System.out.println(sum(1, 2, 3));      // calls the third
    }
}

Varargs String...

T... is internally a T[] array; you can pass any number of arguments of that type. A varargs parameter must be the last in the list.

// Varargs.java
public class Varargs {
    static int max(int... nums) {
        if (nums.length == 0) {
            throw new IllegalArgumentException("need at least one");
        }
        int m = nums[0];
        for (int n : nums) {
            if (n > m) m = n;
        }
        return m;
    }

    public static void main(String[] args) {
        System.out.println(max(3, 1, 4, 1, 5, 9, 2, 6));  // 9

        // you can also pass an array directly
        int[] arr = {7, 2, 8};
        System.out.println(max(arr));                      // 8
    }
}

static Methods vs Instance Methods

A static method belongs to the class, called via ClassName.method, and cannot access instance fields; an instance method belongs to an object and requires a new XX() first. Chapter 6 covers classes and objects; here we just compare usage.

// StaticVsInstance.java
public class StaticVsInstance {
    private String name;

    public StaticVsInstance(String name) {
        this.name = name;
    }

    void hello() {  // instance method
        System.out.println("hi, " + name);
    }

    static String capitalize(String s) {  // static method
        return s.substring(0, 1).toUpperCase() + s.substring(1);
    }

    public static void main(String[] args) {
        // static called directly
        System.out.println(capitalize("alice"));   // Alice

        // an instance method requires new first
        StaticVsInstance obj = new StaticVsInstance("Bob");
        obj.hello();
    }
}

Parameter Passing Mechanism

Java is always "pass by value". But for reference types, a copy of the reference is passed — inside the function you can mutate the object through the reference, but reassigning obj = new ... does not affect the outside.

// PassByValue.java
import java.util.ArrayList;
import java.util.List;

public class PassByValue {
    static void changeInt(int n) {
        n = 99;  // modifies the local copy
    }

    static void mutateList(List<Integer> list) {
        list.add(99);  // mutates the object's internals via the reference
    }

    static void reassignList(List<Integer> list) {
        list = new ArrayList<>();  // reassigns the local reference; no effect outside
        list.add(-1);
    }

    public static void main(String[] args) {
        int n = 1;
        changeInt(n);
        System.out.println(n);             // 1

        List<Integer> nums = new ArrayList<>(List.of(1, 2, 3));
        mutateList(nums);
        System.out.println(nums);          // [1, 2, 3, 99]
        reassignList(nums);
        System.out.println(nums);          // [1, 2, 3, 99] unchanged
    }
}

Method References Class::method

Since Java 8 a method can be passed as a "value". Four forms: Class::staticMethod, obj::instanceMethod, Class::instanceMethod, Class::new. Chapter 14 on Lambdas goes deeper.

// MethodRef.java
import java.util.List;

public class MethodRef {
    public static void main(String[] args) {
        List<String> names = List.of("Alice", "Bob", "Carol");

        // method reference: System.out::println is equivalent to s -> System.out.println(s)
        names.forEach(System.out::println);

        // static method reference: Integer::parseInt is equivalent to s -> Integer.parseInt(s)
        List<String> nums = List.of("1", "2", "3");
        int sum = nums.stream().mapToInt(Integer::parseInt).sum();
        System.out.println("sum=" + sum);
    }
}