Declaring arrays without using the 'new' keyword in Java Declaring arrays without using the 'new' keyword in Java arrays arrays

Declaring arrays without using the 'new' keyword in Java


There is the obvious difference that one has all zeros, and the other contains [1..5].

But that's the only difference. Both are 5-element int arrays, both are allocated in the same way. It is mere syntactic convenience to declare with the braces and no new.

Note that this form can only be used when the array is declared:

int[] blah = {}

But not

int[] blah;blah = {};

or

return {};

Objects (arrays are objects) are allocated on the heap.


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.


I agree with the other answers, by far the most often you array will be allocated on the heap (no matter which of the two declarations you use). However, according to the top answer in Can Java allocate a list on stack?, “in special cases, the java virtual machine may perform escape analysis and decide to allocate objects … on a stack”. I believe that this is true. So the answer to your question is: It depends. Usually on the heap.