javaarraysreturn-value

Storing a returned array in Java


import java.io.*;
class test
{

    int[] returnArray()
    {
        int[] arr={1,2,3,4,5,6,7,8,9,10};
        return arr;
    }

    void display(int[] arr)
    {
        for(int i=0;i<arr.length;i++)
        {
            System.out.print(arr[i]+"\t");
        }
    }

    public static void main(String[] args)
    {
        test obj=new test();
        int[] arr=new int[1];

        arr=obj.returnArray();
        obj.display(arr);
    }
}

In the above code, I am storing the returned array in an array of size 1, whereas the size of the returned array is 10. Still, the returned array is printed in full i.e. it's being stored fully in 'arr' array.

I was expecting it to give some error like array out of bounds or storing only one element as corresponding to the size of the array.


Solution

  • You're assigning the returned array to the arr variable. The previous array it was referencing (the one created by new int[1]) is no longer accessible after the assignment, and is eligible for garbage collection.