Search code examples
javaarraysprogramming-languagesmethods

How to store an array returned by a method in Java


I want to store the array returned by a method into another array. How can I do this?

public int[] method(){
    int z[] = {1,2,3,5};
    return z;
}

When I call this method, how can I store the returned array (z) into another array?


Solution

  • public int[] method() {
        int z[] = {1,2,3,5};
        return z;
    }
    

    The above method does not return an array par se, instead it returns a reference to the array. In the calling function you can collect this return value in another reference like:

    int []copy = method();
    

    After this copy will also refer to the same array that z was refering to before.

    If this is not what you want and you want to create a copy of the array you can create a copy using System.arraycopy.