Why I am able to pass a bigger array into a smaller array in Java?

Viewed 1967

This might be a silly question but does a Java array accept more than its size? If yes then why do we need ArrayList? I thought that arrays had a fixed size that can't be increased at runtime. Here is my test code:

public class ArraySizeDemo {
    int[] anArray = new int[5];

    public int[] getAnArray() {
        return anArray;
    }

    public void setAnArray(int[] anArray) {
        this.anArray = anArray;
    }
}

public class ArrayDemo {
    public static void main(String[] args) {
        ArraySizeDemo ar = new ArraySizeDemo();

        int arr[] = {0,1,2,3,4,5,6,7,8,9};
        int testarray[] = new int[10];
        ar.setAnArray(arr); // it should give an error here since I am trying to 
        // assign an array of 10 to an array of 5
        testarray = ar.getAnArray();
        for (int i = 0; i < arr.length; i++)
            System.out.println(testarray[i]);
    }
}
5 Answers

As others have said, the statement: this.anArray = anArray or, in general any statement of type: array[x] = array[y]

does not copy element's of one array to another. The assignment operator, here, simply references(provides location/address of) one array to other.

A clear in-depth explanation about this is provided here (archived)

Related