Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

why object defined in the method are created in the heap memory?

 
James Tharakan
Ranch Hand
Posts: 580
Eclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator



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 ?
 
Mohamed Sanaulla
Saloon Keeper
Posts: 3159
33
Google App Engine Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Objects are always stored on the heap.
 
Abimaran Kugathasan
Ranch Hand
Posts: 2066
Clojure IntelliJ IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I suggest you to go through the JVM Specification for these kind of JVM architecture questions.
 
Stephan van Hulst
Bartender
Pie
Posts: 5898
63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Leon Omk
Ranch Hand
Posts: 75
Chrome Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Good example. So only references to the instances are removed from stack when methods return, but instances can be "re-used" because there are still stored in heap.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic