I am doing some studying and I came across a question that asks to show the correct memory diagram of the following code:
int [] d1 = new int[5];
d1[0] = 3;
Integer [] d2 = new Integer[5];
d2[0] = new Integer(3);
ArrayList d3 = new ArrayList();
d3.add(3);
Here is my attempt at a memory diagram, but it may be incorrect:
I understand things like objects, instance variables, and "new" instances are all on the heap and things such as local variables and primitive types are on the stack, but I'm still confused when it comes to array types.
Any help is appreciated.
Arrays are not primitive in java it has concrete class in java.
So when you create Object of any array type it must go to you heap space.
Here is an alternate, correct memory diagram.
Any Object on Java lives on heap.
In Java Array is also an Object and hence array Object lives on heap.
Explaination:-
When you write
the (new int[5]) part creates object and hence lives on heap.
is also an Object(remember new Operator will always create new Object).
and hence when you wright,
it is Array of Integer Object.
As far as ArrayList is considered it is also a class but it wraps array Object and adds dynamic memory to it. So,
again creates Object and hence live on heap.
Consider ArrayList class as:
so when you write d3.add(5) actually d3.add(new Integer(5)) is being called.
Remember one golden rule: In java whatever Object you create live on HEAP and their reference live on stack.
Proof of array being object:-
//prints true