Declaring arrays without using the 'new' keyword in Java

前端 未结 5 2152
执念已碎
执念已碎 2020-12-14 17:15

Is there any difference between the following two declarations?

int arr[] = new int [5];

and

int arr1[] = {1,2,3,4,5};
         


        
5条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-14 17:36

    The first line puts one new object on the heap -an array object holding four elements- with each element containing an int with default value of 0.

    The second does the same, but initializing with non default values. Going deeper, this single line does four things:

    • Declares an int array reference variable named arr1
    • Creates an int array with a length of five (five elements).
    • Populates the array's elements with the values 1,2,3,4,5
    • Assigns the new array object to the reference variable arr1

    If you use an array of objects instead of primitives:

    MyObject[] myArray = new MyObject[3];
    

    then you have one array object on the heap, with three null references of type MyObject, but you don't have any MyObject objects. The next step is to create some MyObject objects and assign them to index positions in the array referenced by myArray.

    myArray[0]=new MyObject();
    myArray[1]=new MyObject();
    myArray[2]=new MyObject();
    

    In conclusion: arrays must always be given a size at the time they are constructed. The JVM needs the size to allocate the appropriate space on the heap for the new array object.

提交回复
热议问题