Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do Java functions duplicate arrays passed by arguments when returning them?

Tags:

java

arrays

I read that Java passes arrays to functions by reference (sort of) and it allows modification on it which would be reflected on the original array.

Well I'm not sure about the reference part in the above link because someone else said that Java is always pass by value, with no exceptions, ever. However I know for sure that modification on the argument array changes the original array too.

So does that mean that when I return the same array that was passed through arguments, Java would return a duplicate of the original array? and while not doing that and using the original array instead will save me some memory and CPU usage? or does Java duplicate the array in both cases?

For example are the following two functions identical or does the first one save memory and cpu resources?:

public void modifyArray (int[] arr)
{
    for (int i = 0; i < arr.length; i++) arr[i] = i + 1;
}

public int[] modifyArray (int[] arr)
{
    for (int i = 0; i < arr.length; i++) arr[i] = i + 1;
    return arr;
}

Edit:

Just to be more clear, I am only concerned about the performance (especially when dealing with large arrays) and I don't actually need to copy the array, I have an existing code that does this and want to know if removing the retun part would improve performance.

like image 644
razz Avatar asked Sep 10 '26 09:09

razz


1 Answers

Java passes the reference by value. Which means that replacing the array does no harm, i.e.

public void f(String[] a)
{
   a = new String[42];
}

but changing anything in it will change the original array. Deep copying of general objects can be very time consuming and is also difficult in cases where objects contain objects which reference objects ... so that the standard behaviour is to avoid it.

like image 189
J Fabian Meier Avatar answered Sep 12 '26 00:09

J Fabian Meier



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!