Pass array by reference in Java

60,464

Solution 1

private void demo() {
    int[] array = new int[5];
    System.out.println(Arrays.toString(array)); // 0, 0, 0, 0, 0
    fillArray(array);
    System.out.println(Arrays.toString(array)); // 0, 1, 2, 3, 4
}

private void fillArray(int[] array) {
    for (int i = 0; i < array.length; i++) {
        array[i] = i;
    }
}

Arrays are objects in Java. And references to objects are passed by value.

Solution 2

In Java, an array is passed by value, but the value is a reference to an array. Suppose you have an array arr. When you pass it, you can change the array that arr refers to, but you cannot change which array arr refers to; i.e. inside a method, you can modify the referenced object but you cannot modify the passed variable that will still be a reference to the same object. I will try to illustrate with an example:

public static void swap(StringBuffer a, StringBuffer b)
{
    StringBuffer t = a;
    a = b;
    b = t;
}

public static void change(StringBuffer a, StringBuffer b)
{
    a = a.append("1");
    b = b.append("2");
}

public static void main(String[] args)
{
    StringBuffer a = new StringBuffer("First");
    StringBuffer b = new StringBuffer("Second");
    swap(a, b);
    System.out.println(a + " " + b);
    change(a, b);
    System.out.println(a + " " + b);
}

Output:

First Second
First1 Second2

You can see from the example that First Second is obtained in the output instead of Second First. This is because in the function swap, copies have been used which have no impact on the references in the main. Thus illustrating the fact that you cannot modify the passed variable that will still be a reference to the same object. However, the function change brings about the desired effect because you can modify the referenced object.

For more reference see this:
Is Java “pass-by-reference”?

Solution 3

Java is pass by value. This reference will be passed by value, that is copied. It will still point at the original array.

int[] arrayToPass

Solution 4

This might be an unpopular way of thinking about it, but being from a C/C++ side myself, it made it easier for me.

In Java, objects are reference types. Meaning that the actual object is on the heap somewhere, and what you actually use is just a reference to that object. Thus it is simpler to think of it in terms of C pointers (as an analogy).

Classname object;

would behave similar to the below in C/C++

Classname *object;

Similarly, in the case of functions, they behave as if the parameters of the function are passed as pointers. Similar to how you would simulate pass-by-reference in C:

void Function(Classname object)

It is more like the below C version

void Function(Classname *object)

And as long as you don’t change the value of the pointer itself (in java by reallocating the variable with a new instance) you can use it to access and modify the original instance.

And to wrap it all up, all types other than the primitive types (int, double,boolean, etc.) are reference types (even types like Integer, Double, Boolean, and arrays).

So as others have explained already, you don’t need to add the & for it to behave as you would expect (except certain caveats like reassignment with a new instance).

Share:
60,464
maryam
Author by

maryam

Updated on July 05, 2022

Comments

  • maryam
    maryam almost 2 years

    Is it OK to pass an array as an argument in Java, like int[5] &result?

    I want to pass the reference to the array because I want to change the array in the calling function. What would the syntax be?

  • RNJ
    RNJ over 11 years
    Yes you're right now I think about it. I was thinking about non arrays
  • T.J. Crowder
    T.J. Crowder over 11 years
    @RNJ: Even with non-arrays, it made no difference. But you're right that Java is purely pass-by-value.
  • T.J. Crowder
    T.J. Crowder over 11 years
    "When you pass it, you can change the array that arr refers to, but you cannot change which array arr refers to." Quite right, but could be a lot clearer (for those who get confused about this stuff).
  • Brian Roach
    Brian Roach over 11 years
    Why? There's not a problem with passing an array; it's an object the same as a List
  • cavila
    cavila over 11 years
    You right just pass the array direct since it is asking to change the self array.
  • bane
    bane over 11 years
    @T.J.Crowder Took your advice and tried to explain it more clearly.
  • MFARID
    MFARID over 9 years
    But you need to create the elements of the array first before you pass it by reference (i.e., you can't pass a null array)
  • rayryeng
    rayryeng over 9 years
    Thank you for this. I found this to be more clearer than the highest upvoted answer. Very nice explanation!
  • Sahib Khan
    Sahib Khan over 7 years
    And references to objects are passed by value. What you mean by this? it should be passed by reference not by value
  • JB Nizet
    JB Nizet over 7 years
    You can think it should be passed by reference if you want, but that's not what the Java designers think, and that's not how Java works. When you pass an array to a method, you're actually passing a copy of a reference to that array. The calling method can use the reference to change the content of the array, but if it assigns a different array to the reference, the caller won't be affected, and the original reference in the callig method will still point to the original array.
  • Twisted Code
    Twisted Code over 2 years
    @JBNizet I think they might've been trying to say that your wording seemed contradictory. At least, it seemed contradictory to me until I read one of the other answers. Assuming it wasn't an unmarked direct quote from anywhere, could you perhaps clarify the wording in your post to something like "arrays are objects in Java, which are accessed by reference. This reference is passed by value, meaning the reference can't be changed but the same object is accessed"? (I'm not sure if this is the best wording. Hence why I'm not suggesting an edit)
  • Dave S
    Dave S over 2 years
    I think it would be clearer also if you changed the parameter names to x and y rather than a and b. For example, in the swap method, it would be clear that assigning a new value to x will not have any affect outside the scope of the method. In the change method it's irrelevant whether you assign a new value to x or simply execute x.append("1"). The scope of x will end with the method but the affect of the append modifies the original argument.