• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Stack Vs Heap

 
Prashant Sehgal
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I hope I am not falling too much out of line here, but coming from a programming background involving both C++ and Java, my question is about how Stack and Heap are treated differently in both languages.
I read in a post somewhere that...
".... Java programmers moving to C++. Since in Java all your classes are created with "new" I doubt Java programmers come to C++ with much of an idea of the difference between stack and heap allocation and what should go where (I often wondered how Java could get away with this until I realized that Java uses a different heap structure... Doh.)..."
Firstly, can anyone explain the exact difference between Stack and Heap? Also, can anyone please explain what sort of a "heap-structure" is used in Java?
Thanks.
 
James Clinton
Ranch Hand
Posts: 190
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I can part answer this question.
The heap is used for objects that are created dynamically at run-time. All objects in Java are like this as they are created using the new key word.
//C++ has both.
Object o = new Object() //c++ or java dynalic obj
//C++ object on stack
Object o; // if used in java this would result in a null pointer, but is valid in C++.

Dynamic objects in java are therefore used and then removed when null by the garbo collector. C++ coders would specifically have to "delete" the object to avoid memory leeks.
The stack is used for objects that the computer knows the size of, I *think* all static types in Java are stored there. (behind the scenes they are essentially memery addresses with pointers attached to them, java programers are shielded from this thou).
Pls correct me if I'm wrong.
/James
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Prashant, Welcome to JavaRanch!
I seem to recall seeing this topic discussed a few times recently, and in the more distant past. Try a quick search on this forum, and on the Intermediate forum. Note that the search page link is at the top right of this page.
 
peter greaves
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
>The stack is used for objects that the computer knows the size of, I *think* all static types in Java are stored there
james - did you mean, "objects that the COMPILER knows the size of, " ??

peter
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic