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?
It is mere syntactic convenience to declare with the braces and no new . return {}; Objects (arrays are objects) are allocated on the heap.
To create an array value in Java, you use the new keyword, just as you do to create an object. Here, type specifies the type of variables (int, boolean, char, float etc) being stored, size specifies the number of elements in the array, and arrayname is the variable name that is the reference to the array.
There are two ways you can declare and initialize an array in Java. The first is with the new keyword, where you have to initialize the values one by one. The second is by putting the values in curly braces.
JAVA Programming Array can be initialized when they are declared. Array can be initialized using comma separated expressions surrounded by curly braces. It is necessary to use new operator to initialize an array.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With