Topic 75 of 119 7. Arrays and Strings in Java Interactive Tutorial

Passing Arrays to Methods in Java: Reference Passing and Returns

9 mins read Last updated: 22 Aug 2026 27,975 views

Direct Answer & Core Concept

Arrays can be passed to methods in Java just like other variables. When an array is passed to a method, the method receives a copy of the array reference, which allows it to access the same array object.

This is important because changes made to array elements inside a method are visible to the caller. Java is technically pass-by-value, including when the value being passed is an array reference.

Detailed Explanation & Mechanics

What Does Passing an Array to a Method Mean?

Passing an array to a method means giving the method access to an existing array. The method can read the array, modify its elements, search it, calculate values, or perform other operations.

You do not need to create another array just to pass it to a method. The array variable can be supplied directly as an argument.

Main.java
Run Online
int[] numbers = {
    10, 20, 30
};
printArray(numbers);

Here, numbers is passed to the printArray() method.


Basic Syntax for Passing an Array

The array type is written in the method parameter just like it is written when declaring an array variable.

Main.java
Run Online
static void printArray(int[] numbers) {
    // method body
}

You can call the method like this:

Main.java
Run Online
int[] numbers = {
    10, 20, 30
};
printArray(numbers);

The method parameter numbers receives a copy of the reference to the original array object.


Simple Example of Passing an Array

Let's create a method that prints every element of an integer array.

Main.java
Run Online
public class ArrayMethodExample {
    static void printArray(int[] numbers) {
        for (int number : numbers) {
            System.out.println(number);
        }
    } public static void main(String[] args) {
        int[] numbers = {
            10, 20, 30, 40
        };
        printArray(numbers);
    }
}

Output:

The main() method passes the array to printArray().


Arrays Are Objects in Java

An array is an object in Java. An array variable does not directly contain all of its elements; instead, it contains a reference to the array object.

For example:

Main.java
Run Online
int[] numbers = {
    10, 20, 30
};

Conceptually:

When you pass numbers to a method, the reference value is copied.


Java Uses Pass-by-Value

One of the most important concepts is that Java is always pass-by-value.

When you pass an array to a method, Java copies the value of the reference into the method parameter. Both the original variable and the parameter can therefore refer to the same array object.

Main.java
Run Online
int[] numbers = {
    10, 20, 30
};
changeArray(numbers);

Conceptually:

Architecture Diagram
main()                 method()
numbers ───────┐       numbers ───────┐
               └──────> [10, 20, 30] <┘

There are two reference variables, but only one array object.


Why Can a Method Change the Original Array?

Because the method parameter refers to the same array object, changing an element changes that shared object.

Main.java
Run Online
static void changeArray(int[] numbers) {
    numbers[0] = 100;
}public static void main(String[] args) {
    int[] numbers = {
        10, 20, 30
    };
    changeArray(numbers);
    System.out.println(numbers[0]);
}

Output:

The original array now contains 100 at index 0.


Important: Java Does Not Pass the Array Object by Reference

It is common to say that Java "passes arrays by reference," but this is technically inaccurate.

Java passes the value of the array reference by value. The copied reference still points to the same array object, which is why element modifications are visible outside the method.

This distinction becomes important when you reassign the parameter itself.


Modifying Array Elements Inside a Method

A method can directly modify individual array elements.

Main.java
Run Online
static void update(int[] numbers) {
    numbers[0] = 100;
    numbers[1] = 200;
}

Calling it:

Main.java
Run Online
int[] numbers = {
    10, 20, 30
};
update(numbers);

After the method finishes:

The original array has been modified.


Changing Every Element

You can use a loop to modify every element.

Main.java
Run Online
static void doubleValues(int[] numbers) {
    for (int i = 0;
    i < numbers.length;
    i++) {
        numbers[i] = numbers[i] * 2;
    }
}

Example:

Main.java
Run Online
int[] numbers = {
    1, 2, 3, 4
};
doubleValues(numbers);

The array becomes:

This is useful when a method is intended to update an existing array.


Reading an Array Inside a Method

A method does not have to modify an array. It can simply read its values.

Main.java
Run Online
static int calculateSum(int[] numbers) {
    int sum = 0;
    for (int number : numbers) {
        sum += number;
    } return sum;
}

Call the method:

Main.java
Run Online
int[] numbers = {
    10, 20, 30
};
int result = calculateSum(numbers);
System.out.println(result);

Output:

The method reads the array but does not change it.


Finding the Maximum Value

Arrays can be passed to methods that calculate useful results.

Main.java
Run Online
static int findMaximum(int[] numbers) {
    int max = numbers[0];
    for (int number : numbers) {
        if (number > max) {
            max = number;
        }
    } return max;
}

Usage:

Main.java
Run Online
int[] numbers = {
    10, 45, 20, 90, 30
};
int maximum = findMaximum(numbers);
System.out.println("Maximum = " + maximum);

Output:

This keeps the calculation separate from the main() method.


Finding the Minimum Value

The same approach can be used to find the smallest element.

Main.java
Run Online
static int findMinimum(int[] numbers) {
    int min = numbers[0];
    for (int number : numbers) {
        if (number < min) {
            min = number;
        }
    } return min;
}

Example:

Main.java
Run Online
int[] numbers = {
    50, 20, 80, 10, 40
};
System.out.println(findMinimum(numbers));

Output:


Searching an Array Using a Method

You can pass an array and a search value to a method.

Main.java
Run Online
static boolean contains(int[] numbers, int target) {
    for (int number : numbers) {
        if (number == target) {
            return true;
        }
    } return false;
}

Call it:

Main.java
Run Online
int[] numbers = {
    10, 20, 30, 40
};
System.out.println(contains(numbers, 30));

Output:

Returning boolean makes the method simple and reusable.


Returning an Array from a Method

A Java method can return an entire array.

The return type is written as int[], String[], or another array type.

Main.java
Run Online
static int[] createArray() {
    int[] numbers = {
        10, 20, 30
    };
    return numbers;
}

You can receive the returned array like this:

Main.java
Run Online
int[] result = createArray();

The method returns the reference to the array object.


Returning a New Array

A method can create and return a new array directly.

Main.java
Run Online
static int[] createNumbers() {
    return new int[] {
        10, 20, 30, 40
    };
}

Use it like this:

Main.java
Run Online
int[] numbers = createNumbers();
for (int number : numbers) {
    System.out.println(number);
}

This technique is useful when a method needs to generate a collection of values.


Returning a Modified Array

A method can modify an existing array and return it.

Main.java
Run Online
static int[] doubleValues(int[] numbers) {
    for (int i = 0;
    i < numbers.length;
    i++) {
        numbers[i] *= 2;
    } return numbers;
}

Usage:

Main.java
Run Online
int[] numbers = {
    1, 2, 3
};
int[] result = doubleValues(numbers);

In this example, returning the array is not strictly necessary because the original array was already modified.


Returning a Completely New Array

Sometimes you should create a new array instead of changing the original one.

Main.java
Run Online
static int[] doubleValues(int[] numbers) {
    int[] result = new int[numbers.length];
    for (int i = 0;
    i < numbers.length;
    i++) {
        result[i] = numbers[i] * 2;
    } return result;
}

Now the original array remains unchanged.

Main.java
Run Online
int[] numbers = {
    1, 2, 3
};
int[] result = doubleValues(numbers);

The arrays are:

Main.java
Run Online
numbers →[1, 2, 3]result →[2, 4, 6]

This approach is useful when you want to avoid modifying input data.


Original Array vs New Array

Consider these two approaches carefully.

Modifying the original array

Main.java
Run Online
static void update(int[] numbers) {
    numbers[0] = 100;
}

The caller's array changes.

Creating a new array

Main.java
Run Online
static int[] update(int[] numbers) {
    int[] result = new int[numbers.length];
    result[0] = 100;
    return result;
}

The original array remains unchanged.

The correct approach depends on whether your method is designed to mutate or preserve the input.


Reassigning an Array Parameter

This is where the pass-by-value concept becomes especially important.

Consider:

Main.java
Run Online
static void changeReference(int[] numbers) {
    numbers = new int[] {
        100, 200, 300
    };
}

Now call:

Main.java
Run Online
int[] numbers = {
    10, 20, 30
};
changeReference(numbers);
System.out.println(numbers[0]);

Output:

Why?

The method receives a copy of the reference. Reassigning that copied reference does not change the original variable in main().


Modification vs Reassignment

These two operations behave differently.

Modifying an element

Changes the shared array object.

Reassigning the parameter

Main.java
Run Online
numbers = new int[] {
    100, 200
};

Changes only the local parameter variable.

This is one of the most important concepts when learning how Java passes arrays to methods.


Visualizing Pass-by-Value with Arrays

Suppose:

Main.java
Run Online
int[] numbers = {
    10, 20, 30
};

Then:

Conceptually:

Architecture Diagram
Before method:

main
numbers ──────────────┐
↓
[10, 20, 30]


Inside method:

main                      method
numbers ────────┐         numbers ───────┐
                └──────────────┐         │
↓

↓
[10, 20, 30]

Both references point to the same array object.

If the method executes:

the shared object becomes:


Passing a String Array to a Method

Arrays of objects can also be passed to methods.

Main.java
Run Online
static void printNames(String[] names) {
    for (String name : names) {
        System.out.println(name);
    }
}

Call it:

Main.java
Run Online
String[] names = {
    "Rahul", "Priya", "Amit"
};
printNames(names);

The same array-passing principle applies to String[] and other object arrays.


Passing a Character Array

A char[] can also be passed to a method.

Main.java
Run Online
static void printCharacters(char[] letters) {
    for (char letter : letters) {
        System.out.print(letter + " ");
    }
}

Example:

Main.java
Run Online
char[] letters = {
    'J', 'a', 'v', 'a'
};
printCharacters(letters);

Output:

The parameter type simply needs to match the array type.


Passing a 2D Array to a Method

Two-dimensional arrays can also be passed to methods.

Main.java
Run Online
static void printMatrix(int[][] matrix) {
    for (int[] row : matrix) {
        for (int value : row) {
            System.out.print(value + " ");
        } System.out.println();
    }
}

Call it:

Main.java
Run Online
int[][] matrix = {
{
        1, 2, 3
    }, {
        4, 5, 6
    }
};
printMatrix(matrix);

This is useful for keeping matrix-processing logic organized.


Returning a 2D Array

A method can also return a two-dimensional array.

Main.java
Run Online
static int[][] createMatrix() {
    return new int[][] {
{
            1, 2, 3
        }, {
            4, 5, 6
        }
    };
}

Use it like this:

Main.java
Run Online
int[][] matrix = createMatrix();

The syntax is:

Main.java
Run Online
returnType methodName() {
    return array;
}

For a 2D integer array, the return type is int[][].


Passing Multiple Arrays to a Method

A method can accept multiple arrays as parameters.

Main.java
Run Online
static void compareArrays(int[] first, int[] second) {
    System.out.println("First length: " + first.length);
    System.out.println("Second length: " + second.length);
}

Call it:

Main.java
Run Online
int[] a = {
    1, 2, 3
};
int[] b = {
    4, 5, 6, 7
};
compareArrays(a, b);

Methods can combine arrays with other parameter types as well.


Passing an Array with Other Parameters

An array does not have to be the only method parameter.

Main.java
Run Online
static void printElements(int[] numbers, String title) {
    System.out.println(title);
    for (int number : numbers) {
        System.out.println(number);
    }
}

Usage:

Main.java
Run Online
int[] numbers = {
    10, 20, 30
};
printElements(numbers, "Numbers:");

This pattern is common in practical Java programs.


Varargs and Arrays

Java provides variable-length arguments, called varargs, using ....

Main.java
Run Online
static int sum(int... numbers) {
    int total = 0;
    for (int number : numbers) {
        total += number;
    } return total;
}

You can call it with individual values:

Main.java
Run Online
System.out.println(sum(10, 20, 30));

You can also pass an existing array:

Main.java
Run Online
int[] numbers = {
    10, 20, 30
};
System.out.println(sum(numbers));

Inside the method, numbers is treated as an array.


Array Parameter with final

You can declare an array parameter as final.

Main.java
Run Online
static void print(final int[] numbers) {
    // ...
}

This prevents the parameter variable from being reassigned inside the method.

For example, this is not allowed:

Main.java
Run Online
numbers = new int[] {
    1, 2, 3
};

However, final does not make the array elements immutable.

This is still allowed:

So final protects the reference from reassignment, not the contents of the array.


Returning null from an Array Method

A method can technically return null for an array.

Main.java
Run Online
static int[] getNumbers(boolean available) {
    if (!available) {
        return null;
    } return new int[] {
        10, 20, 30
    };
}

The caller must handle the possibility of a null result.

Main.java
Run Online
int[] numbers = getNumbers(false);
if (numbers != null) {
    System.out.println(numbers.length);
}

In many designs, returning an empty array can be safer than returning null when there is simply no data.


Returning an Empty Array

Instead of returning null, a method can return an empty array.

Main.java
Run Online
static int[] getNumbers() {
    return new int[0];
}

The array exists but contains no elements.

Main.java
Run Online
int[] numbers = getNumbers();
System.out.println(numbers.length);

Output:

This can simplify calling code because the caller can safely use loops without first checking for null.


Passing an Array to a Method Does Not Copy the Array

Consider:

Main.java
Run Online
int[] a = {
    1, 2, 3
};
int[] b = a;

No new array is created.

Both variables point to the same array:

Architecture Diagram
a ─────┐
↓
[1, 2, 3]
       ↑
b ─────┘

The same idea applies when passing an array to a method.

If you need an independent copy, explicitly create one.


Copying an Array Before Passing It

You can create a copy using Arrays.copyOf().

Main.java
Run Online
import java.util.Arrays;
int[] original = {
    10, 20, 30
};
int[] copy = Arrays.copyOf(original, original.length);

Now:

Main.java
Run Online
original →[10, 20, 30]copy →[10, 20, 30]

They are separate array objects.

Changes to copy do not change original.


Method That Returns a Copy of an Array

You can create a reusable method that returns an independent copy.

Main.java
Run Online
import java.util.Arrays;
static int[] copyArray(int[] numbers) {
    return Arrays.copyOf(numbers, numbers.length);
}

Usage:

Main.java
Run Online
int[] original = {
    10, 20, 30
};
int[] copy = copyArray(original);
copy[0] = 100;

Now:

Main.java
Run Online
original →[10, 20, 30]copy →[100, 20, 30]

Passing Arrays to Methods: Complete Example

Here is a complete program showing several common operations.

Main.java
Run Online
public class ArrayMethods {
    static void printArray(int[] numbers) {
        for (int number : numbers) {
            System.out.print(number + " ");
        } System.out.println();
    } static int calculateSum(int[] numbers) {
        int sum = 0;
        for (int number : numbers) {
            sum += number;
        } return sum;
    } static void doubleValues(int[] numbers) {
        for (int i = 0;
        i < numbers.length;
        i++) {
            numbers[i] *= 2;
        }
    } static int[] createArray() {
        return new int[] {
            100, 200, 300
        };
    } public static void main(String[] args) {
        int[] numbers = {
            10, 20, 30
        };
        System.out.println("Original array:");
        printArray(numbers);
        int sum = calculateSum(numbers);
        System.out.println("Sum = " + sum);
        doubleValues(numbers);
        System.out.println("After modification:");
        printArray(numbers);
        int[] newArray = createArray();
        System.out.println("Returned array:");
        printArray(newArray);
    }
}

Output:

Main.java
Run Online
Original array:10 20 30Sum = 60After modification:20 40 60Returned array:100 200 300

Common Mistakes

Mistake 1: Forgetting the Array Type

Incorrect:

Main.java
Run Online
static void print(numbers) {
}

Correct:

Main.java
Run Online
static void print(int[] numbers) {
}

The method parameter must specify the array type.


Mistake 2: Thinking Java Passes Arrays by Reference

A common shortcut is saying "arrays are passed by reference." The more precise explanation is that Java passes the reference value by value.

This explains both behaviors: element changes are visible, but parameter reassignment is not reflected in the caller's variable.


Mistake 3: Reassigning the Parameter and Expecting the Caller to Change

This does not replace the caller's array:

Main.java
Run Online
static void replace(int[] numbers) {
    numbers = new int[] {
        100, 200
    };
}

The reassignment affects only the local parameter.


Mistake 4: Accidentally Modifying the Original Array

If a method changes:

the caller's array can also change because both references point to the same array.

If you do not want this behavior, create a copy first.


Mistake 5: Returning an Array Without Understanding Ownership

When a method returns an array, the caller receives a reference to that array.

If the returned array is mutable, the caller can change its contents.

Design your method carefully when the array represents internal or shared state.


Best Practices

Use methods to separate array operations such as searching, sorting, calculating sums, and printing. This makes the program easier to read and allows the same operation to be reused.

Clearly decide whether a method should modify the original array or return a new array. If mutation is unexpected, create a copy instead.

For methods that do not need to modify an array, treat the parameter as read-only by convention and avoid changing its elements.


Passing Arrays vs Returning Arrays

FeaturePassing ArrayReturning Array
DirectionCaller → MethodMethod → Caller
Common purposeProcess existing dataProduce data
Can modify original?YesDepends on returned object
Uses reference valueYesYes
ExampleprintArray(numbers)return numbers

Both mechanisms are commonly used together in Java programs.


Key Difference: Element Change vs Reference Change

Remember this simple rule:

Changes the array object.

But:

Main.java
Run Online
numbers = new int[] {
    100, 200
};

Changes only the local reference variable.

This distinction explains most confusion around Java arrays and method parameters.


Frequently Asked Questions

Are arrays passed by reference in Java?

Technically, no. Java is always pass-by-value. For arrays, the value being passed is a copy of the reference to the array object.

Can a method modify an array?

Yes. A method can modify array elements, and those changes are visible to the caller because the method and caller can refer to the same array object.

Can a method return an array?

Yes. A method can return arrays such as int[], String[], double[], or int[][].

How do I pass an array to a method?

Pass the array variable as an argument:

Main.java
Run Online
int[] numbers = {
    1, 2, 3
};
printArray(numbers);

The method parameter might be:

Main.java
Run Online
static void printArray(int[] numbers)

Does Java copy an array when passing it to a method?

No new array is automatically created. Java copies the reference value, so the method can access the same array object.

What happens if I reassign an array parameter?

Reassigning the parameter changes only the local parameter variable. It does not replace the caller's original array variable.

How can I prevent a method from changing the original array?

Create a copy before modifying it:

Main.java
Run Online
int[] copy = Arrays.copyOf(numbers, numbers.length);

Then operate on copy.

Can I pass a 2D array to a method?

Yes.

Main.java
Run Online
static void printMatrix(int[][] matrix) {
    // ...
}

You can pass a 2D array using:

Can a method return a 2D array?

Yes.

Main.java
Run Online
static int[][] createMatrix() {
    return new int[][] {
{
            1, 2
        }, {
            3, 4
        }
    };
}

What is the difference between an array parameter and a varargs parameter?

An array parameter requires an array:

Main.java
Run Online
static void print(int[] numbers)

A varargs parameter can accept individual values or an array:

Main.java
Run Online
static void print(int... numbers)

Inside the method, varargs are handled as an array.


Practice Questions

  1. Create a method that prints all elements of an integer array.

  2. Create a method that returns the sum of an array.

  3. Create a method that returns the largest element.

  4. Create a method that returns the smallest element.

  5. Create a method that searches for a number.

  6. Create a method that doubles every element in an array.

  7. Create a method that reverses an array.

  8. Create a method that returns a copy of an array.

  9. Create a method that returns a new array containing only even numbers.

  10. Pass a 2D array to a method and print it.

  11. Create a method that calculates the sum of every row.

  12. Demonstrate the difference between modifying an array element and reassigning an array parameter.

  13. Write a method using varargs to calculate the average of numbers.

  14. Create a method that returns an empty array when no data is available.

  15. Write a method that takes two arrays and returns a combined array.


Quick Revision

The most important concept in this topic is that Java is always pass-by-value.

When an array is passed to a method, the value being copied is the array reference. Therefore, the method can access and modify the same array object.

Main.java
Run Online
static void update(int[] numbers) {
    numbers[0] = 100;
}

But reassigning the parameter does not change the caller's variable:

Main.java
Run Online
static void replace(int[] numbers) {
    numbers = new int[] {
        100, 200
    };
}

Methods can also return arrays:

Main.java
Run Online
static int[] createArray() {
    return new int[] {
        10, 20, 30
    };
}

Remember:

Main.java
Run Online
Pass array↓Copy reference value↓Same array object↓Element changes are visible

But:

Main.java
Run Online
Reassign parameter↓Only local reference changes↓Caller reference remains unchanged

Once you understand this difference, passing and returning arrays in Java becomes much easier.


Graphic and Image Design Ideas

Graphic 1: Passing an Array to a Method

Create a visual showing:

Architecture Diagram
main()

numbers
   │
   ▼
[10] [20] [30]
   ▲
   │
method(numbers)

Add a label: "Copied reference → same array object".

Graphic 2: Java Pass-by-Value Explanation

Use a two-column diagram:

Architecture Diagram
main()                    method()

numbers ──────┐          numbers ──────┐
              └───────────────┐        │
                              ▼        ▼
                           [10, 20, 30]

Explain that the reference value is copied, not the entire array.

Graphic 3: Modify vs Reassign

Show two side-by-side examples:

Main.java
Run Online
MODIFY REASSIGNnumbers[0] = 100 numbers = new int[] {
    ...
}Same array changes Local reference changes

This is the most important visual for this topic.

Graphic 4: Returning an Array

Show:

Architecture Diagram
Method
  │
  │ creates
  ▼
[10, 20, 30]
  │
  │ return
  ▼
Caller

Label it "Returning an array reference".

Graphic 5: Original Array vs Copy

Show:

Main.java
Run Online
Original →[10, 20, 30]Copy →[10, 20, 30]

Then show an update:

Main.java
Run Online
Original →[10, 20, 30]Copy →[100, 20, 30]

Label them as "Two separate array objects".

Graphic 6: 2D Array Passed to Method

Show:

Architecture Diagram
main()
   │
   ▼
┌─────────┐
│ 1 2 3   │
│ 4 5 6   │
└─────────┘
   │
   ▼
printMatrix(matrix)

This visually connects the topic with the previous Multidimensional Arrays in Java chapter.

Runnable Code Example: Passing Arrays to Methods in Java

Java 17+
Main.java
Run Online
import java.util.Arrays;
public class PassArrayDemo {
    public static void doubleElements(int[] arr) {
        for (int i = 0;
        i < arr.length;
        i++) {
            arr[i] *= 2;
            // Mutates original array elements
        }
    } public static void main(String[] args) {
        int[] values = {
            1, 2, 3, 4
        };
        doubleElements(values);
        System.out.println("Doubled: " + Arrays.toString(values));
        // [2, 4, 6, 8]
    }
}

Common Java Technical Interview Questions & Answers

Interview Prep
Q1

Does reassigning an array parameter inside a method (arr = new int[10];) affect the caller?

No, because Java is Pass by Value; reassigning the parameter reference variable only changes the local copy.
Q2

What is defensive copying for arrays in getters?

Returning a clone of an internal array field to prevent external code from modifying private class state.

Key Takeaways, Best Practices & Clean Code Rules

Java Best Practice & Production Rules

Always return a defensive clone (arr.clone() or Arrays.copyOf()) from getter methods when returning mutable array fields.