Stage 1: Java fundamentals, lesson 6 of 10

Methods and pass-by-value

Beginner3 min readall versions
Explain it forThe essentials plus production detail and pitfalls.

A method has a return type, a name, parameters and a body. Methods with the same name but different parameter lists are overloaded.

Java is always pass-by-value. For primitives, the value is copied. For objects, the reference is copied: the method can change the object's contents, but reassigning the parameter never changes the caller's variable.

static methods belong to the class, like Math.max. Instance methods need an object. Varargs (int... nums, Java 5) accept any number of arguments.

Anatomy of a method

A method has modifiers, a return type (void for none), a name, parameters and a body. return ends the method and hands back a value.

Java
public static double withGst(double price, double rate) {
    if (price < 0) throw new IllegalArgumentException("price can't be negative");
    return price * (1 + rate);
}

Java is always pass-by-value

Java copies every argument. For primitives it copies the value. For objects it copies the reference, so the method can change the object the reference points to, but reassigning the parameter doesn't affect the caller's variable.

Java
static void change(int n, List<String> list) {
    n = 99;                 // caller's int is unchanged
    list.add("added");      // caller sees this: same object
    list = new ArrayList<>(); // caller's variable is unchanged
}

Method overloading

Several methods can share a name if their parameter lists differ (number, types or order). The return type alone isn't enough. The compiler picks the best match, preferring an exact match, then widening, then boxing, then varargs.

Java
static int area(int side) { return side * side; }
static int area(int w, int h) { return w * h; }
static double area(double radius) { return Math.PI * radius * radius; }

area(4);        // int version
area(4, 5);     // two-int version
area(2.5);      // double version

Varargs

type... name accepts any number of arguments, received as an array. Only the last parameter can be varargs.

Java
static int sum(int... numbers) {
    int total = 0;
    for (int n : numbers) total += n;
    return total;
}
sum();            // 0
sum(1, 2, 3);     // 6
sum(new int[]{4, 5});

Static vs instance methods

A static method belongs to the class and is called on it (Math.max(a, b)); it can't use this. An instance method works on one object's data and is called on that object (name.length()). Utility functions are static; behaviour tied to an object's state is instance.

Returning several values

A method returns one value, but that value can be a record holding several. It's clearer than arrays or out-parameters.

Java
record MinMax(int min, int max) {}

static MinMax range(int[] values) {
    int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;
    for (int v : values) { min = Math.min(min, v); max = Math.max(max, v); }
    return new MinMax(min, max);
}

var r = range(new int[]{4, 9, 1});
System.out.println(r.min() + " to " + r.max());

Example

Java
static void rename(StringBuilder sb) {
    sb.append(" Sharma");            // changes the shared object
    sb = new StringBuilder("X");     // only changes the local copy
}

static int sum(int... nums) {        // varargs
    int s = 0;
    for (int n : nums) s += n;
    return s;
}

StringBuilder name = new StringBuilder("Riya");
rename(name);
System.out.println(name);            // Riya Sharma
System.out.println(sum(1, 2, 3));    // 6

Common mistake

Writing swap(int a, int b) and expecting the caller's variables to swap. Only the copies inside the method are swapped.

Under the hood

Each call pushes a stack frame holding parameters and local variables; very deep recursion ends in StackOverflowError. The JIT inlines small, frequently called methods, so splitting code into small, well-named methods costs nothing at runtime.

Check yourself

A method does list = new ArrayList<>() on its parameter. The caller's list is…

How this connects

Part of Java from zero.

Was this lesson helpful?

Finished reading? Mark it complete to track your progress.