Suprakash Pal Suprakash Pal - 12 days ago 5
Java Question

can we resize an array in java?

can we resize an array in java? if not, explain this:

int arr[] = new int[1];
arr[0]=-10;
//arr[1]=1;
arr=new int[2]; //Explain this
arr[0]=-1;
arr[1]=1;
System.out.println(arr[0]+" "+arr[1]);

Answer

Resizing an array is impossible, as far as I'm concerned.

To understand why your code works, you need to understand that arrays are reference types. arr holds an reference to the actual array, like this:

      holds                points to
arr ----------> reference -----------> array object

In this line:

arr=new int[2];

You are not doing anything to the array object at the very end there. You're basically saying:

Hey arr. I don't want you to hold that reference anymore. Let go and hold this reference (which is an array with length 2)!

"What happens to the original array object with length 1 then?" you asked. This is where the GC comes into place. At some point, objects that has no reference pointing to, are collected.

Comments