Muhammad Ali Qadri Muhammad Ali Qadri - 3 months ago 9
Java Question

Declaring arrays without using the 'new' keyword in Java

Is there any difference between the following two declarations?

int arr[] = new int [5];


and

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


Is
arr1
declared on stack or on the heap?

Answer

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 (*).


(*) As pointed out in this answer, objects can very occasionally be allocated on the stack, if escape analysis determines that it is safe to do so without changing the program's semantics. However, this is an unusual case, so you can generally assume that an object will be allocated on the heap.