As i understand , the Object aa defined in the method is created in the heap memory and the reference of it is stored in the stack memory. Why is it created in the heap memory and why it is not created in the stack memory itself. Because, as the method returns the reference will removed , which makes the object ready for GCed. So i was thinking why not it be created in the stack memory at the first place.
And where are the object 'a' and its reference created? stack or heap.
Basically what is the logic that defines that the particular object should be defined in the stack or heap ?
Why to worry about things in which we dont have control, Why to worry about things in which we have control ! !
Let's assume for a moment that objects may indeed be allocated on the stack:
Now, myObj would be on the stack. And it will get deleted again once doSomething() returns. What should doSomeMore() do to preserve the value so it can be printed in the main method?
The only way this can happen is if enough space is on the heap *somewhere* that can hold obj (and we don't even know how much space this has to be, since the Object passed to doSomeMore could just as well be a String or any other subclass of Object); and we copy the contents of obj into object, whenever an assignment is made.
Let's say we could magically predict how much space has to be available (through a size variable in Object?), wouldn't you agree that having to copy the entire value of an object is extremely wasteful, compared to just copying a reference? And you *have* to copy the value, because the value ceases to exist once the method is popped from the stack.
The mind is a strange and wonderful thing. I'm not sure that it will ever be able to figure itself out, everything else, maybe. From the atom to the universe, everything, except itself.