Method Parameters in Java β€” Pass-by-value Explained

Java is always pass-by-value. For primitives, the value is the number. For objects, the value is the reference (a handle pointing to the object). Mutating the object through that reference is visible to the caller; reassigning the parameter is not.

Primitives β€” a copy is passed

static void setFive(int x) { x = 5; }

int n = 10;
setFive(n);
System.out.println(n);          // 10 β€” caller's variable unchanged

Objects β€” the reference is copied, the object is shared

static void mutate(StringBuilder sb)  { sb.append("!"); }
static void reassign(StringBuilder sb) { sb = new StringBuilder("nope"); }

var sb = new StringBuilder("hi");
mutate(sb);
reassign(sb);
System.out.println(sb);         // "hi!" β€” mutate worked, reassign didn't

Immutable parameters β€” defensive practice

public void process(final List<String> items) {
    // items cannot be reassigned inside this method
    for (String s : items) { ... }
}

Some teams require final on every parameter. It prevents accidental reassignment but adds noise β€” opinions vary.

Wrappers and autoboxing

static void addOne(Integer i) {
    i = i + 1;                  // boxes the new value, reassigns the local
}                               // caller sees nothing β€” Integer is immutable anyway

Returning multiple values

Java has no out parameters. Return an object instead:

public record Split(String head, String tail) {}

public Split split(String s, char sep) {
    int i = s.indexOf(sep);
    return new Split(s.substring(0, i), s.substring(i + 1));
}

Varargs

Zero or more arguments of the same type, collected into an array:

public static int sum(int... nums) { ... }
sum(1, 2, 3);

See the full varargs page.

Common mistakes

  • Expecting out parameters β€” they don't exist. Return a value, or a record if you need multiple.
  • Mutating a defensive copy instead of the caller's data β€” usually intentional, sometimes a surprise.
  • Too many parameters β€” if a method takes six arguments, consider a parameter object or builder.
  • Null as a signal value β€” use Optional or an overload that doesn't take the parameter.

Related

Pillar: Java methods. See also varargs, overloading.