Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading