• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

heap and stack?

 
Ranch Hand
Posts: 206
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Can somebody tell me what is heap and stack in java?
 
Ranch Hand
Posts: 142
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The heap is a place in memory were space is allocated and initialized when you use the 'new' statement. Stack is where automaticly created local variables are stored. Hence on the heap you can find the data of the created objects, and on the stack go the local vars.

Example: if you have a method foo like

foo() {
MyClass myO1 = new MyClass;
int i=3;
MyClass myO2 = null;

}

The bit pattern of reference myO1 goes on the stack. But the pattern points to a place on the heap where the actual MyClass data of myO1 is. The primitive i goes on the stack, the latter represents by its bit pattern the number 3, and is not pointer to a place on the heap. myO2 does not refer to anything yet, since you do not let it point to anything. The bit pattern of myO2 is a whole lot of zero's.

So now you have on the heap one Object of MyClass. On the stack you have a reference myO1 that points to that spot. On the stack you have a primitive i which has a bit patterns that litterally represents the number 3, and on the stack you have a reference myO2 that is kinda empty, in the sence that it does not refer to anything.
 
God is a comedian playing for an audience that is afraid to laugh - Voltair. tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic