Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array size changing after creation

Tags:

java

arrays

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();       
    }
}
like image 810
Ammar Avatar asked Feb 19 '26 05:02

Ammar


1 Answers

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

like image 90
DarthVader Avatar answered Feb 20 '26 18:02

DarthVader



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!