To understand what is going on, you first need to understand what variables really exist. A variable is a placeholder for a value. And what is this value? For value types, a value is an instance of the value type itself; for reference types, a value is simply the memory address, so to speak, of the object to which it refers.
So, when you do the following:
int[] a = new int[2];
Since arrays are reference types, the value stored in a is the address of the newly created array.
Then when you do:
a = new int[4];
The only thing you do is overwrite the value stored in a , which we indicated as just the address of the object referenced.
What happens to the original array? Absolutely nothing, he lives blissfully happy, not knowing that you just reassigned a link pointing to this. If there are no other live links in the original array, then the GC can, if it so decided, compile it, but when that happens, it completely depends on the GC (it may not even happen during the life of your application).
source share