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.
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
nullfor 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
- Confusing pass-by-value with pass-by-reference — Java is always pass-by-value, never pass-by-reference
- Modifying a returned collection — changes affect all code holding that reference unless you return a copy
- Varargs ambiguity with overloads — multiple varargs overloads can cause compilation ambiguity
- Returning mutable static state — a method that returns a static collection gives all callers a view into the same object
- Not checking for null before streaming —
nullStreamcauses 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
Optionalfor 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
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.".size() or .isEmpty() on an empty collection without NPE. For optional values, Optional.empty() is preferred over null."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."Function<T, R>, Consumer<T>, or Predicate<T>."null behave when passed as an argument?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."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."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."print(a, b, c) instead of print(new String[]{a, b, c}."Further Reading
- Method Overloading — varargs ambiguity and overload resolution
- Static Methods — static methods and their interaction with parameters
- Lambda Expressions — passing behavior as parameters with lambdas
- Method References — constructor references for object creation
- Java SE 27 Record API — records have been available since Java 16
- Java SE 27 JLS, method invocation — argument evaluation and method invocation
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.
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 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.