can anyone explain whats happening here. I was under the impression that an array's size can't be changed once its been created and declared.
public class ArrayManipulation
{
public static void main(String[] args)
{
int a[] = {1, 2, 3};//new int[3];
int b[] = new int[a.length-1];
System.out.print("a = ");
for (int i = 0; i < a.length; i++)
System.out.print(a[i] + " ");
System.out.println();
for (int i = 0; i < b.length; i++)
b[i] = a[i];
//This is the bit I am confused about.. I was expecting an error here
a = b;
System.out.print("a = ");
for (int i = 0; i < a.length; i++)
System.out.print(a[i] + " ");
System.out.println();
}
}
Arrays are objects, and yes, once they are created their size doesnt change.
in the line:
a= b;
you are pointing a reference to b object. So your initial object that a was referencing is still in VM until it s garbage collected.
But your array size didnt change but you reference is pointing to a differet array/object now
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With