Reputation: 626
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?
Upvotes: 31
Views: 20098
Reputation: 140319
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.
Upvotes: 37
Reputation: 29285
new int [5]
can be used for both assignment and initialization, but {1, 2}
only can be used as declaration with initialization. (Note that new int[] {1, 2}
also can be used as both assignment and initialization)
new int [5]
sets all entries to zero, but {1, 2}
and new int[] {1, 2}
sets 1
and 2
in respective entries.
Both are on heap, you can save their object reference.
int arr[] = new int [5];
// arr: object reference to the array
or
int arr[] = {1, 2, 3, 4, 5};
// arr: object reference to the array
Helpful materials:
Upvotes: 4
Reputation: 86306
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.
Upvotes: 4
Reputation: 640
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:
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.
Upvotes: 8
Reputation: 1090
Objects
reside in heap
. Arrays
are object type
in java programming language. Official documentation here
Upvotes: 3