BeginnerLesson 5 of 204 min read

Methods: Parameters, Return Values and Pass by Value

Learn to write methods, overload them, return values and see that Java passes copies of values, with a real program that proves it and a second check by counting calls.

In this lesson you will

  • Write and call methods
  • Overload a method
  • Explain pass by value
  • Return values and use them

About 28 minutes

One price rule, used everywhere

Hana’s price rule appears in the booking screen, the invoice and the monthly report. If she copies the same lines into three places, a change means three edits and one is sure to be forgotten. A method gives a name to a piece of logic so that you write it once and use it everywhere. It has a name, parameters, a return type and a body.

Parameters are the inputs, and the return value is the output. A method that returns nothing has the return type void. Overloading means giving several methods the same name with different parameter lists, and the compiler picks the one that matches the call. Variables declared inside a method are local, and they disappear when the method ends. Many beginners worry about whether Java passes by value or by reference, and the answer is that it always passes by value: the method receives a copy of whatever you hand in. For a primitive, the copy is the number itself. For an object or an array, the copy is a copy of the reference, the address, so the method and the caller both point at the same object.

You pass The method receives Changing the parameter
An int A copy of the number Does not change the caller’s variable
An array or object A copy of the reference Changing the contents is visible to the caller
An array or object A copy of the reference Pointing the parameter at a new object is not visible
public class Main {
    static int calls = 0;
    static int price(int days) { calls++; return days * 12; }
    static double price(int days, double discount) { calls++; return days * 12 * (1 - discount); }
    static void addOne(int x) { x = x + 1; System.out.println("inside addOne: " + x); }
    static void fill(int[] a) { for (int i = 0; i < a.length; i++) a[i] = 7; }
    static void replace(int[] a) { a = new int[] {9, 9, 9}; System.out.println("inside replace: " + a[0]); }
    public static void main(String[] args) {
        System.out.println("3 days: " + price(3));
        System.out.println("5 days, 10% off: " + price(5, 0.10));
        int n = 5;
        addOne(n);
        System.out.println("after addOne: " + n);
        int[] data = {1, 2, 3};
        fill(data);
        System.out.println("after fill: " + data[0] + data[1] + data[2]);
        replace(data);
        System.out.println("after replace: " + data[0]);
        System.out.println("price() was called " + calls + " times");
    }
}
3 days: 36
5 days, 10% off: 54.0
inside addOne: 6
after addOne: 5
after fill: 777
inside replace: 9
after replace: 7
price() was called 2 times

The two overloads were chosen by the arguments: price(3) used the one-parameter method and gave 36, and price(5, 0.10) used the two-parameter version and gave 54.0. The counter confirms that each ran once, 2 calls in total.

The pass-by-value rules show in the rest of the output. addOne changed its own copy to 6, but after the call the caller’s n is still 5. The fill method changed the contents of the array through the reference it was given, so the caller sees 777, which is 7, 7, 7. The replace method pointed its own parameter at a new array of nines and printed 9 inside, but that does not affect the caller, whose array is still full of sevens, and the output shows 7. So the precise statement is that Java passes a copy of the reference, which lets a method change the object but not the caller’s variable.

Check by hand: 3 x 12 = 36, and 5 x 12 x (1 – 0.1) = 60 x 0.9 = 54. The counter started at 0 and went up once per price call, so after two calls it is 2.

Why this design is useful

Passing copies keeps methods predictable. When you call a method with a number, you know for certain that your own variable will not change behind your back. With objects you must remember that the method may change the contents, which is why well-written methods say so in their name or their documentation, for example fill or addOne, and why later lessons introduce immutable objects that cannot be changed at all.

Do not rely on parameters to return results

Assigning to a parameter changes only your copy. Return the new value instead, and let the caller store it.

Give methods one job and a clear name

A method called priceForDays is easier to test and reuse than one called doStuff that also prints and saves.

About this course

Every program in this lesson was compiled and run with OpenJDK 21 while the course was written. Java releases twice a year, so check the official Java documentation for the current version and for features added after Java 21.

Practice

Write a method isWeekend(String day) that returns a boolean, and a method that takes an array of rental lengths and returns the total price. Call each from main and check them against a calculation by hand.

Check what you learned

Five quick questions. Pick an answer and you will see straight away whether it is right and why.

What does a method with return type void return?

  1. Zero
  2. Nothing
  3. An empty string
  4. An error

It is used for its effects.

What is method overloading?

  1. Same name, different parameters
  2. Two classes
  3. A very long method
  4. A method that loops

The compiler picks by the arguments.

Does Java pass by value or by reference?

  1. Always by value
  2. Always by reference
  3. By value for text only
  4. By reference for numbers

For objects, the value is a copy of the reference.

What happened to n after addOne(n)?

  1. It became 6
  2. It became 0
  3. It was deleted
  4. It stayed 5

The method changed a copy.

Why does fill(data) change the caller’s array?

  1. Arrays are copied
  2. Java uses globals
  3. It is a bug
  4. Both refer to the same array

The reference was copied, not the array.

Summary

  • A method names a reusable piece of logic.
  • Overloading uses the same name with different parameters.
  • Java always passes copies: values for primitives, references for objects.
  • Return values instead of changing parameters.

Next lesson

Lesson 6 covers arrays, the simplest way to hold many values.

Questions

What is a local variable?

A variable declared inside a method. It exists only while the method runs.

What is recursion?

A method calling itself, with a stopping condition. A later lesson uses it.

Can a method return more than one value?

Not directly. Return an object, a record or an array that holds them.

Progress is saved in this browser.