If you’ve been developing in Java-like languages and never had anything to do with memory management, you may not know what the stack and the heap are and what they do.

// Java
public void changeGear(int gear) {  
    Gearbox gb = new Gearbox();
    gb.setGear(gear);
}

The heap is the easiest to explain, it’s a big pile of memory, in your computer RAM, reserved for your application. This piece of memory gets reserved at the moment you run your application and it is done by your operating system. Any memory the application uses, for example objects, comes from this ‘heap’. The Gearbox object in the above example would be on this heap. You can’t really do anything to control whether or not this object will be on the heap, it just will. If needed, the heap can be expanded on run time, which also is done by the operating system.

The name 'heap’ comes from the fact that each piece of the memory can be accessed at any given moment, for both reading and writing. There isn’t any required order for reading or writing, it is just a big pile of memory for you to use.

The other option would be the stack, which is a far smaller piece of memory, also located in your computer RAM, which controls your application’s execution path. For example, the stack from an application driving a car could look like this:

putKeyInIgnition()  
     startCar()
         changeGears(1)
             accelerate()

The stack is used for keeping track of which method (or function) is being called and can be used to store local variables. The size of the stack is constant for an application and is small, around 2MB for Java on a desktop pc, which is enough for most applications.

The name 'stack’ comes from the manner in which the memory is read from and written to. It works 'LIFO’, or 'Last In, First Out’, which means new data will always be written to the end of the stack and the last piece of written data will always be removed first.

A stack can be thought of as a pile of post-its. When a method or function is called, a new post-it is created and stuck to any previous post-its. Any local variables are written on this post-it and when the method or function is done, the entire post-it it is removed. While on a post-it, the previous post-it cannot be written to or read from.

Jeff Hill made a nice post about the stack and the heap on Stackoverflow.