CodeGym /Courses /JAVA 25 SELF /Passing parameters by value and by reference

Passing parameters by value and by reference

JAVA 25 SELF
Level 8, Lesson 4
Available

1. Introduction

In different programming languages there are two main ways to pass parameters into functions (or methods):

  • By value: the function receives a copy of the variable’s value. If the function changes the parameter, the original does not change.
  • By reference: the function receives a “reference” (pointer) to the original object. Changes inside the function are reflected in the original.

In Java ALL parameters are passed by value!
But there is a catch: when we pass primitive types (int, double, boolean, etc.), the value itself is copied. And when we pass reference types (for example, arrays or objects), the value of the reference (that is, the object’s “address” in memory) is copied, not the object itself.

If you feel your brain starting to melt, don’t worry — we are about to break it down and show it with examples!

2. Primitive types: the value is copied

Let’s start simple: what happens if we try to change the value of a variable of type int inside a method?

public class Demo 
{
    public static void main(String[] args) 
    {
        int number = 5;
        changeValue(number);
        System.out.println(number); // What will be printed?
    }

    public static void changeValue(int n) 
    {
        n = 42;
    }
}

Result: 5 will be printed.

Why?
A COPY of the value of the variable number is passed into the changeValue method. Inside the method we change only the copy (n); the original variable number in main remains untouched.

Analogy
Imagine you gave a friend a photocopy of your passport, not the original. Your friend can draw a moustache on the copy as much as they like — your real passport stays the same!

3. Reference types: the reference is copied

Now try the same with an array:

public class Demo 
{
    public static void main(String[] args) 
    {
        int[] numbers = {1, 2, 3};
        changeFirst(numbers);
        System.out.println(numbers[0]); // What will be printed?
    }

    public static void changeFirst(int[] arr) 
    {
        arr[0] = 99;
    }
}

Result: 99 will be printed.

Why?
A copy of the REFERENCE to the array numbers is passed to the changeFirst method. Both names (numbers in main and arr in the method) point to the same array in memory. Therefore, if we change an array element inside the method, the change is “visible” outside.

Visualization

main: numbers ──► [1, 2, 3]
                   ▲
                   │
changeFirst: arr ──┘
The copied reference points to the same object in memory

By changing arr[0], we are actually changing numbers[0], because both point to the same object.

4. But if you change the reference itself — the original object will not change!

Now let’s try this:

public class Demo 
{
    public static void main(String[] args) 
    {
        int[] numbers = {1, 2, 3};
        replaceArray(numbers);
        System.out.println(numbers[0]); // What will be printed?
    }

    public static void replaceArray(int[] arr) 
    {
        arr = new int[] {10, 20, 30};
    }
}

Result: it prints 1.

Why?
In the replaceArray method, the variable arr starts pointing to a new array, but that does not affect the variable numbers in main.
They were connected by the same reference, but when we assign arr = ... inside the method, that is only a local change.

Analogy
It is as if you and a friend had the same key to an apartment. Your friend made themselves a new key, but your old key remained the same — and the door is the same.

5. Practice examples: you cannot “swap” two int via a method

Many beginners try to write a method to swap two numbers, but it doesn’t work:

public class Demo 
{
    public static void main(String[] args) 
    {
        int a = 5, b = 10;
        swap(a, b);
        System.out.println(a + " " + b); // Expected: 10 5, but actually?
    }

    public static void swap(int x, int y) 
    {
        int temp = x;
        x = y;
        y = temp;
    }
}

Result: 5 10 will be printed.

Why?
Because swap receives copies of variables a and b. Everything we do inside swap affects only those copies, not the originals.

6. But with arrays you can change the contents!

Here’s the proper way to swap values in an array:

public class Demo 
{
    public static void main(String[] args) 
    {
        int[] arr = {5, 10};
        swap(arr);
        System.out.println(arr[0] + " " + arr[1]); // Expected: 10 5
    }

    public static void swap(int[] arr) 
    {
        int temp = arr[0];
        arr[0] = arr[1];
        arr[1] = temp;
    }
}

Result: it prints 10 5.

Why?
Because we are changing the contents of the object (array) that both the original variable and the method parameter point to.

7. Demonstration: objects and their fields

Arrays are clear. What about objects of our own classes? It’s exactly the same!

class Box 
{
    int value;
}

public class Demo
{
    public static void main(String[] args) 
    {
        Box box = new Box();
        box.value = 7;
        changeBox(box);
        System.out.println(box.value); // What will be printed?
    }

    public static void changeBox(Box b) 
    {
        b.value = 42;
    }
}

Result: it prints 42.

Why?
Because we are changing a field of the object that the reference points to.

What happens when parameters are passed to methods

What we pass What gets copied Can we modify it inside the method? Are the changes visible outside?
int, double, etc. Copy of the value Yes, but only the copy No
Array Copy of the reference Yes, if you change elements Yes
Object (class) Copy of the reference Yes, if you change fields Yes
Array/object Copy of the reference No, if you assign a new reference No

8. Common mistakes

Mistake #1: expecting an int to change after a method call. Many beginners think that if you pass a variable of type int to a method, you can change its value inside the method. That’s incorrect: only the copy changes!

Mistake #2: trying to swap two int via a method. As we have already seen, this is impossible — only the copies of the variables swap places; the originals are unaffected.

Mistake #3: trying to “replace” an array via a method. If you assign a new array to the array parameter inside the method (arr = new int[]{...}), this will not affect the original array. To “replace” an array, you need to return a new array from the method and assign it to the variable in the calling code.

Mistake #4: forgetting that you can change an object’s contents. If you pass an object (or array), remember that any changes to its fields/elements will be visible from the outside!

Mistake #5: confusion about null. If you pass a reference equal to null into a method and try to access its fields, you will get a NullPointerException. Be careful!

1
Task
JAVA 25 SELF, level 8, lesson 4
Locked
Reset the robot's starting point on the trajectory 🤖
Reset the robot's starting point on the trajectory 🤖
1
Task
JAVA 25 SELF, level 8, lesson 4
Locked
Attempt to update player's bonus list 🎁
Attempt to update player's bonus list 🎁
1
Task
JAVA 25 SELF, level 8, lesson 4
Locked
Swapping players in a soccer team ⚽
Swapping players in a soccer team ⚽
1
Task
JAVA 25 SELF, level 8, lesson 4
Locked
Updating the contents of the magical chest 📦
Updating the contents of the magical chest 📦
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION