Skip to content
Tutorials Center
My learning

Topics

Lesson 39 of 201 ยท Methods

Parameters and Return Values

Pass data into Java methods and get results back - parameters vs arguments, return rules, why Java is always pass-by-value, and returning several values with records.

A method that always does exactly the same thing is of limited use. printBanner() from Methods prints one fixed title. Real methods take input that changes from call to call and often produce output: Math.max(a, b) takes two numbers and gives back the larger one. Parameters are how data goes in; return values are how results come out.

This lesson covers both in detail: declaring parameters and passing arguments, the rules for return, and the one idea that trips up more Java developers than any other: Java always passes arguments by value, even when those values are references to objects. You'll finish by returning several values at once with a record.

Parameters and arguments

A parameter is a variable declared in the method header. An argument is the actual value you pass when calling the method. On each call, Java evaluates the arguments and uses them to initialize the parameters, in order:

Java Parameters receive the arguments

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

  • Each parameter has its own type, even when they repeat: (int a, int b), never (int a, b).
  • Arguments are matched by position, not by name. Java has no named arguments, so printInvoiceLine(3, "Notebook", 2.50) is a compile error, and two parameters of the same type passed in the wrong order compile silently into a bug. Keep parameter lists short and in a natural order.
  • An argument must be assignable to its parameter type. An int argument is fine for a double parameter, because it widens automatically. The reverse is not: passing a double such as price - 4.99 to an int parameter is a compile error unless you cast. See Type Casting and Conversion.
  • The number of arguments must match. For methods that accept any number of values, like String.format, see Varargs.
  • Parameters are local variables of the method. They exist only during the call, and the argument variables in the caller can have completely different names.

How many parameters is too many? Three is comfortable, four or five is a warning sign, and beyond that callers can't remember the order. Group related values into a record or class (Address instead of street, city, zip, country).

Returning a value

A method with a non-void return type must hand back a value of that type with a return statement. return ends the method immediately and delivers the value to the caller, where the call expression evaluates to it:

Java Return values are expressions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The results can be stored, combined in expressions, passed straight into other methods, or chained (initials(...).toLowerCase()). Calling a value-returning method as a plain statement is legal; the result is discarded. Usually that's a mistake, especially with immutable types: name.trim(); on its own does nothing useful, because trim returns a new string.

The rules of return

The compiler checks that every path through a non-void method ends in a return (or a throw). This fails to compile, because when n is 0 the method falls off the end:

Java
String sign(int n) {
    if (n > 0) {
        return "positive";
    } else if (n < 0) {
        return "negative";
    }
}   // error: missing return statement

Add a final return "zero"; and it compiles. The compiler doesn't reason about values, so even if (n > 0) ... if (n <= 0) ... with two returns gets the same error. Use else or a final return.

Other rules worth knowing:

  • The value must match the return type. Returning a long from an int method needs a cast; returning an int from a double method widens automatically.
  • No code after a return in the same block. Statements right after an unconditional return are a compile error (unreachable statement).
  • void methods can use a bare return; to leave early, which is handy for guard clauses:
Java
void printReceipt(double[] prices) {
    if (prices.length == 0) {
        IO.println("Nothing bought.");
        return;                       // leave the method now
    }
    // ... print the receipt
}

Early returns for special cases at the top of a method (often called guard clauses) keep the main logic unindented and easy to read. A loop can also return the moment it finds an answer, as in break, continue and Labels.

Java is always pass-by-value

When you call a method, Java copies the value of each argument into the parameter. That's the whole rule, with no exceptions. What surprises people is what that value is:

  • For a primitive (int, double, boolean, ...), the value is the number or boolean itself.
  • For a reference type (arrays, String, any object), the value stored in the variable is a reference: the address of an object. Copying it gives the method a second reference to the same object. The object itself isn't copied.

Primitives: the caller's variable is safe

Java Changing a primitive parameter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

points starts as a copy of score. Changing the copy has no effect on score. If you want the caller to get the new value, return it: score = addBonus(score); with int addBonus(int points) { return points + 50; }.

References: the object can change, the variable can't

With an array or object, the method gets a copy of the reference. It can use that reference to change the object, and the caller sees the change, because both references point to the same thing. But assigning a new object to the parameter only redirects the method's copy:

Java Mutating vs reassigning a reference parameter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Picture the call doubleAll(numbers) like this:

TEXT
before:   main: numbers โ”€โ”€โ”
                          โ””โ”€โ”€> [ 1 | 2 | 3 ]
during:   main: numbers โ”€โ”€โ”
                          โ”œโ”€โ”€> [ 2 | 4 | 6 ]    doubleAll writes through its copy
   doubleAll: values  โ”€โ”€โ”€โ”€โ”˜
in replace: values โ”€โ”€> [ 7 | 7 | 7 ]   a new array; numbers still points to [ 2 | 4 | 6 ]

This is why people sometimes say "Java passes objects by reference". It doesn't. In true pass-by-reference (like C++ int& parameters), assigning to the parameter would change the caller's variable, and replace would have changed numbers. In Java it never does. The precise phrase is: Java passes references by value.

A classic consequence: you can't write a swap(a, b) method in Java that swaps two of the caller's variables. You can swap two elements of an array you're given (swap(array, i, j)), because that mutates the shared object.

Immutable objects behave like primitives

String, Integer and the other wrapper classes, LocalDate and records are immutable: they have no methods that change them. A method that receives one can't modify the caller's object at all, so passing them feels exactly like passing a primitive:

Java
void decorate(String s) {
    s = "*" + s + "*";        // builds a new String, rebinds the local copy
}

String title = "News";
decorate(title);
IO.println(title);            // still "News"

Should a method modify its arguments?

Mutating a parameter is sometimes exactly right: Arrays.sort(array) sorts your array in place to avoid copying it. But surprise side effects are a common source of bugs. Some guidelines:

  • Make it obvious. A method that changes its argument should say so in its name and docs (sortInPlace, fillWithZeros, addTo(list)).
  • Prefer returning a new value when it's cheap: int[] doubled(int[] values) that returns a fresh array leaves the caller's data untouched.
  • Copy defensively when you store an array or list you were given, if the caller might keep changing it (Encapsulation shows why).
  • Don't reassign parameters. Reusing a parameter as a scratch variable makes code harder to follow. Some teams mark parameters final to enforce this (The final Keyword Everywhere).

Returning several values

A method returns exactly one value. When you need more than one result, such as a minimum and a maximum, the clean modern answer is a record: a tiny class that just carries named values (Records covers them fully). One line declares it:

Java Return a record instead of juggling values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The record gives every result a name and a type, prints nicely, and the caller reads values with accessor methods like s.max(). Compare the alternatives you'll find in older code:

Approach Problem
return an array int[] { min, max } positions have no names; only works if all values share a type
return a Map or List<Object> no type safety; casts and typos at run time
fill an array the caller passes in ("out parameter") unclear which arguments are inputs and which are outputs
store results in fields hidden state, breaks when two calls overlap

When a method might have no result (searching for something that isn't there), returning an Optional is often clearer than returning null; see Optional.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does this print? void inc(int n) { n++; } then int x = 5; inc(x); IO.println(x);

    The parameter n is a copy of x's value. Incrementing the copy doesn't affect x. Return the new value if the caller needs it.
  2. 2. What does this print? void zero(int[] a) { a[0] = 0; } then int[] arr = {9, 9}; zero(arr); IO.println(arr[0]);

    The method receives a copy of the reference, which points to the same array. Writing a[0] changes that shared array, so the caller sees 0.
  3. 3. What does this print? void reset(int[] a) { a = new int[2]; } then int[] arr = {9, 9}; reset(arr); IO.println(arr[0]);

    Assigning a new array to the parameter only changes the method's copy of the reference. The caller's variable still points to the original {9, 9}.
  4. 4. Why doesn't this compile? int abs(int n) { if (n >= 0) { return n; } if (n < 0) { return -n; } }

    The compiler doesn't reason that the two conditions cover all values. Use else, or end the method with a return.
  5. 5. What is the cleanest way to return a city name and its population from one method?

    A record gives each value a name and a type, with no casts or hidden state. Arrays of Object lose type safety, and fields create shared state.

Summary

  • Parameters are local variables declared in the header; arguments are the values passed in a call, matched by position.
  • return value; ends a method and delivers its result; every path of a non-void method must return or throw, and void methods may use a bare return; to exit early.
  • Java is always pass-by-value: primitives are copied, and for objects the reference is copied.
  • A method can mutate an object it receives (the caller sees the change), but reassigning a parameter never affects the caller's variable.
  • Immutable types like String and records can't be changed through a parameter at all.
  • To return several values, return a record with named components.

Next: Method Overloading, where several methods share one name and Java picks the right one from the arguments.