Suprakash Pal Suprakash Pal - 1 year ago 129
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=new int[2]; //Explain this
System.out.println(arr[0]+" "+arr[1]);

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download