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.