Parameters and Return Values

Master Java method parameters — pass-by-value semantics, varargs, and how to return single or multiple values cleanly, with practical examples.

published: reading time: 17 min read author: Geek Workbench updated: November 20, 2026
Quick Summary

Master Java method parameters — pass-by-value semantics, varargs, and how to return single or multiple values cleanly, with practical examples.

Parameters and Return Values

Every method call is an exchange — you pass data in, and the method hands something back. Understanding exactly how Java handles this exchange is fundamental to writing correct and predictable code.

Introduction

Every method call passes arguments into a method and may return a result. Java is strictly pass-by-value: a primitive value is copied, and for a reference type the reference value is copied, not the object. The caller’s variable and the parameter can therefore refer to the same object, so a mutation is visible through either reference. Assigning another object to the parameter changes only that local parameter; the caller’s variable still refers to its original object.

The parameter list defines what a method needs from its caller. Java supports variable arguments (varargs): String... messages accepts zero or more strings and treats them as an array inside the method. Varargs must be the last parameter, and a method can have only one. A method can return a primitive, object, array, or void (nothing). For a small, cohesive result, a record (available since Java 16) can make named components clear at the API boundary. If an existing domain or result type already represents those values clearly, return that type instead.

This post explains pass-by-value semantics, including the difference between mutating a shared object and reassigning a local parameter. It covers varargs syntax and overload resolution, then looks at return values: when to use void, why empty collections are often better than null, how Optional expresses an absent value, and when a record makes a multi-value result easier to understand.

When to Use

  • Passing data into a method for computation or state mutation
  • Returning a result from a computation or a status indicator
  • When you need to process a variable number of arguments (varargs)

When Not to Use

  • Avoid varargs when fixed arity is clearer — if you always need exactly 2 or 3 arguments, use distinct parameters
  • Avoid returning null for empty collections — return an empty collection instead
  • Avoid out-parameters (passing an object to be mutated) — prefer returning the new value

Pass-by-Value Semantics

Java is strictly pass-by-value. For primitives, the value itself is copied. For reference types, the parameter receives a copy of the reference value, not a copy of the object. The caller’s variable and the parameter can refer to the same object, so a mutation through either reference is visible through the other. Reassigning the parameter only changes the local parameter.

public class PassByValueDemo {
    public static void main(String[] args) {
        int primitive = 10;
        modifyPrimitive(primitive);
        System.out.println(primitive); // 10 — unchanged

        StringBuilder sb = new StringBuilder("hello");
        modifyReference(sb);
        System.out.println(sb); // "hello world" — object mutated
    }

    static void modifyPrimitive(int n) {
        n = 99; // only local copy changed
    }

    static void modifyReference(StringBuilder sb) {
        sb.append(" world"); // mutates the shared object
    }
}
Type What gets copied Effect
Primitive The primitive value Reassigning the parameter changes its local copy, not the caller’s variable
Reference type The reference value Both references can refer to the same object, so mutations are visible through either; reassigning the parameter only changes the local parameter

Varargs

Varargs allow a method to accept zero or more arguments of a specified type.

public class MathUtils {
    // varargs — treated as an array inside the method
    public static int sum(int... numbers) {
        int total = 0;
        for (int n : numbers) total += n;
        return total;
    }

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

Rules:

  • Varargs must be the last parameter in the signature
  • A method can have only one varargs parameter
  • Inside the method, the varargs parameter is accessed as an array
// VALID
public void log(String level, String... messages) { }

// INVALID — varargs must be last
// public void log(String... messages, String level) { }

Returning Single Values

Point is a record here because its named x and y components describe the result directly. Records are available since Java 16; if a project already has a suitable point type, return that type.

record Point(int x, int y) {}

public class PointDemo {
    static int add(int a, int b) {
        return a + b;
    }

    static Point midpoint(Point p1, Point p2) {
        return new Point((p1.x() + p2.x()) / 2, (p1.y() + p2.y()) / 2);
    }

    public static void main(String[] args) {
        System.out.println(add(2, 3));
        System.out.println(midpoint(new Point(0, 2), new Point(4, 6)));
    }
}

This runnable example requires Java 16 or later for records. It prints:

5
Point[x=2, y=4]

Returning Multiple Values

Use a result record when its named components make a small, cohesive result clearer at the API boundary. Records have been available since Java 16. If an existing domain or result type already expresses these values clearly, return it instead.

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

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

// Usage
MinMax result = findMinMax(new int[]{3, 1, 4, 1, 5});
System.out.println(result.min() + " " + result.max()); // 1 5

Option 2 — Use a Map or List:

public Map<String, Integer> minMaxMap(int[] values) {
    // ... computation
    return Map.of("min", min, "max", max);
}

Mermaid Diagram — Pass-by-Value Flow

flowchart TD
    subgraph "Caller Stack Frame"
        A["int x = 10"]
        B["StringBuilder ref"]
    end
    subgraph "Method Stack Frame"
        C["int n = 10<br/><i>copy of value</i>"]
        D["StringBuilder sb<br/><i>copy of reference value</i>"]
    end
    subgraph "Shared Heap"
        O["StringBuilder object"]
    end
    A -->|"pass primitive"| C
    B -->|"reference value"| O
    D -->|"copied reference value"| O
    D -->|"mutate shared object"| O
    C -.->|"local only, no effect on A"| A

Failure Scenarios

Reassigning the parameter changes only its local copy:

static void reassign(List<String> list) {
    list = new ArrayList<>(); // only the local parameter now refers to this list
    list.add("new");          // does not change the caller's original list
}

public static void main(String[] args) {
    List<String> original = new ArrayList<>();
    original.add("original");
    reassign(original);
    System.out.println(original); // ["original"] — unchanged
}

Null pointer from uninitialized return:

public List<String> filterEmpty(List<String> input) {
    // Forgot to handle null input
    return input.stream()
        .filter(s -> !s.isEmpty())
        .toList(); // NPE if input is null
}

Trade-off Table

Approach Pros Cons
Return single primitive Simple, obvious Limited for complex results
Return object/record Type-safe, named result fields Requires a suitable type; reuse an existing one when it already fits
Return array No extra type needed No type safety, fixed size
Use out-parameter (mutate param) Avoids new object Side effects make code harder to reason about
Throw exception for invalid input Explicit failure signal Overuse clutters code

Code Snippets

Defensive parameter validation:

public double calculateAverage(List<Integer> values) {
    if (values == null || values.isEmpty()) {
        return 0.0; // or throw IllegalArgumentException
    }
    return values.stream()
        .mapToInt(Integer::intValue)
        .average()
        .orElse(0.0);
}

Varargs with additional fixed parameter:

public void printReport(String title, String... rows) {
    System.out.println("=== " + title + " ===");
    for (String row : rows) {
        System.out.println(row);
    }
}

printReport("Sales", "Q1: 100", "Q2: 200", "Q3: 150");

Returning optional for nullable result:

public Optional<String> findUserById(int id) {
    return database.containsKey(id)
        ? Optional.of(database.get(id))
        : Optional.empty();
}

Observability Checklist

  • All parameters are validated at method entry
  • Null inputs are handled explicitly — not assumed
  • Return value type matches what is actually returned
  • Collections returned are either immutable or the caller knows not to mutate them
  • Varargs method handles 0 arguments gracefully
  • Documentation states whether null is a valid input

Security Notes

  • Never trust caller-supplied objects — validate before use
  • Do not expose internal collections through return values; return copies or unmodifiable views
  • Parameterized types (List<String>) prevent type confusion attacks
  • Avoid logging full parameter values that may contain sensitive data (PII, credentials)

Pitfalls

  1. Confusing pass-by-value with pass-by-reference — Java is always pass-by-value, never pass-by-reference
  2. Modifying a returned collection — changes affect all code holding that reference unless you return a copy
  3. Varargs ambiguity with overloads — multiple varargs overloads can cause compilation ambiguity
  4. Returning mutable static state — a method that returns a static collection gives all callers a view into the same object
  5. Not checking for null before streaming — nullStream causes NPE at .stream() call

Quick Recap

  • Java is strictly pass-by-value: primitives copy their value, and reference types copy the reference value
  • Caller and parameter can refer to the same object, so mutations are visible through either; assigning a new object to the parameter does not change the caller’s variable
  • Varargs must be the last parameter and are accessed as an array
  • Return empty collections instead of null; use Optional for nullable results
  • Use a result record (available since Java 16) when named components clarify a small, cohesive result; reuse an existing type when it already represents the values clearly

Interview Questions

1. Is Java pass-by-value or pass-by-reference?
Java is strictly pass-by-value. A reference parameter receives a copy of the reference value, not a copy of the object. The caller's variable and the parameter can refer to the same object, so mutations are visible through either reference. Assigning a different object to the parameter changes only the local parameter; the caller's variable is unchanged."

2. Can varargs be used with other parameters?
Yes, but varargs must always be the last parameter in the method signature. For example, void log(String level, String... messages) is valid. You cannot have two varargs parameters in the same method because the compiler would have no way to disambiguate where one ends and the other begins."

3. What is the difference between returning null and returning an empty collection?
Returning null forces the caller to add null checks everywhere, and forgetting one produces an NPE. Returning an empty collection (or array) allows the caller to iterate safely with no special case needed. The caller can also call .size() or .isEmpty() on an empty collection without NPE. For optional values, Optional.empty() is preferred over null."

4. How do you return multiple values from a method in Java?
Use a result record when its named components make a small, cohesive result clearer at the API boundary; for example, public record MinMax(int min, int max) {} gives each value a name. Records have been available since Java 16. If an existing domain or result type already represents the values clearly, return it. Arrays and maps are also possible, though their elements are less explicit at the call site."

5. What happens if you modify a List passed as a parameter?
A reference parameter receives a copy of the reference value. The caller's variable and parameter can refer to the same List, so mutations through the parameter are visible through the caller's variable. If the method assigns a new List to its parameter, only that local parameter changes; the caller's variable still refers to the original List."

6. Can you pass a method as a parameter in Java?
Not directly — Java methods cannot be passed as parameters. You can pass a lambda expression or method reference that implements a functional interface, or you can pass an object with a method that does what you need. Higher-order functions in Java work through functional interfaces like Function<T, R>, Consumer<T>, or Predicate<T>."

7. What is the difference between passing a primitive and passing an object reference?
A primitive parameter receives a copy of its value. A reference parameter receives a copy of the reference value, so it can refer to the same object as the caller's variable. The method can mutate that shared object's state, but assigning a different object to the parameter does not change the caller's variable."

8. Why does Java not support named parameters like some other languages?
Java uses positional arguments — parameters are matched by their position in the call, not by name. This keeps the language simpler and avoids the complexity of resolving named arguments at runtime. It also means parameter names are not part of the method's signature for overload resolution. Methods with the same parameter types in the same order are considered identical."

9. What is a defensive copy and when should you use it?
A defensive copy creates a new instance of an object rather than returning the original reference. Use it when returning mutable internal state — create a new ArrayList, new byte array, etc. This prevents callers from mutating internal state. The same applies to parameters — if you store a reference to a caller-supplied mutable object, you may want to make a copy to avoid external changes affecting your class."

10. How does null behave when passed as an argument?
A null can be passed for any reference type parameter. Inside the method, if you attempt to call a method on null without checking, you get a NullPointerException. Always validate reference-type parameters at method entry if null is not a valid input. For collections, return empty instead of null so callers can iterate safely."

11. Can you pass a primitive by reference in Java?
No. Java is strictly pass-by-value for all types. Primitives are always passed by value (the actual bits are copied). There is no way to pass a primitive by reference in Java. For several related return values, use a result record when named components improve API clarity; records have been available since Java 16. An existing domain or result type is a good choice when it already represents those values clearly. Some APIs simulate pass-by-reference using wrapper objects, but this still passes the reference by value."

12. What is the difference between passing an array and passing a List to a method?
Arrays are fixed-size and mutable; Lists are variable-size and can be immutable (List.of()). When you pass an array, the method can modify its contents, and the changes are visible through the caller's variable. The same applies to a mutable List. Returning a List can provide better type safety and lets you return immutable copies. Arrays support covariance (Object[] from String[]) which loses type information; List<String> from List<String> preserves it."

13. How does String handling differ in pass-by-value semantics?
A String parameter receives a copy of the reference value. Strings are immutable, so operations such as concatenation, substring, and replace return new Strings instead of changing the shared object. Reassigning the parameter to one of those results changes only the local parameter; the caller's variable is unchanged."

14. What is a bulk operation and how does it interact with varargs?
A bulk operation applies an action to each element of a collection. With varargs, you can define methods like void logAll(String... messages) that accept zero or more strings. The varargs parameter is an array inside the method. For bulk operations on collections, use enhanced for-each or streams — varargs is for method parameters, not iteration over collections."

15. How does Java handle method arguments at the JVM level?
At the JVM level, instance methods receive the this reference as a hidden first argument. Static methods receive only their declared parameters. Arguments are passed by value, including reference values. The JVM uses operand stack slots and local variables for parameters."

16. What is the limitation on varargs and how does it interact with overloading?
Varargs must be the last parameter in a method signature, and a method can only have one varargs parameter. When overloading, the compiler resolves to the most specific applicable method — fixed-arity overloads are preferred over varargs. Calling a method with the same arguments that could match both a fixed and varargs overload will match the fixed one. Ambiguous calls between overloaded methods will not compile."

17. What is the effect of returning a primitive vs returning a boxed type?
Returning a primitive avoids boxing overhead. For example, returning int is more efficient than returning Integer. However, returning null for a primitive wrapper is possible (returning Integer) but returning null for a primitive is impossible. Use primitives for performance-critical code, and use boxed types only when you need to represent null or when working with collections that require object types."

18. When should you use an array vs a varargs parameter?
Use an explicit array parameter when the method signature needs to accept an array as a single argument, or when the array type has specific meaning. Use varargs when the method accepts a variable number of arguments of the same type and zero arguments is valid. Varargs is syntactic sugar that makes the call site cleaner — print(a, b, c) instead of print(new String[]{a, b, c}."

19. What is the difference between pass-by-value and pass-by-reference in the context of Java's type system?
Java has primitive types (byte, short, int, long, float, double, boolean, char) and reference types (classes, arrays, interfaces). Every argument is passed by value. For a reference type, the parameter receives a copy of the reference value, so it can refer to the same object as the caller's variable. Mutating that object is visible through both references, but assigning a different object to the parameter does not change the caller's variable."

20. How does the this reference behave in instance methods vs static methods?
In instance methods, this refers to the current instance and is implicitly passed as the first argument by the JVM. In static methods, there is no this — this is not accessible. Accessing this in a static context results in a compile error. This is why instance methods can access instance fields and static methods cannot."

Further Reading

Conclusion

Java passes every argument by value. A reference parameter gets a copy of the reference value, so the parameter and caller’s variable can refer to the same object. Mutations to that object are visible through either reference. Assigning another object to the parameter only changes the local parameter; the caller’s variable still refers to the original object.

Varargs (int...) accepts a variable number of arguments, but it must be the last parameter, and a matching fixed-arity overload takes precedence. For a small, cohesive result, use a record (available since Java 16) when named components improve API clarity. Return an existing domain or result type when it already describes the values well. Empty collections are usually clearer than null, and Optional can represent an absent result.

The caller’s contract matters: validate inputs, document null behavior, and avoid exposing internal mutable state through return values. Defensive copies and unmodifiable views are the standard tools for that.

For related reading: Varargs and overloading interactions are covered in the Method Overloading post, and how static methods differ from instance methods in their ability to access state is covered in the Static Methods post.

Category

Related Posts

Abstract Classes in Java: Interfaces and Composition

Compare Java interfaces, abstract classes, and composition, then see when shared state, default methods, or sealed types change the design choice.

#java-abstract-classes #java #java-fundamentals

Arithmetic Operators in Java: Division, Overflow, Promotion

Compare Java arithmetic with runnable examples of division, negative remainders, overflow, type promotion, and BigDecimal for decimal money.

#java-arithmetic-operators #java #java-fundamentals

Java Array Basics: Length, Bounds, Copies, and Resizing

Learn Java arrays through runtime-sized allocation, bounds checks, aliasing, copying, and the fixed length that distinguishes them from ArrayList.

#java-array-basics #java #java-fundamentals