Home > DeveloperSection > Forums > stack and heap in java
Derek Honeybun
Derek Honeybun

Total Post:17

Posted on    July-13-2015 1:29 AM

 Java Java 

 1 Reply(s)
 840  View(s)
Rate this:
what is difference between stack and heap in Java . Can we create an object in stack memory? 
Does object of private class is also stored in heap memory??

Mayank Tripathi
Mayank Tripathi

Total Post:397

Posted on    July-13-2015 6:51 AM

The stack is where local variables are stored. Each time you call a method, all the variables used by that method (including method parameters) get put on top of the stack. When a method returns, those variables are removed from the top of the stack. That way, the top of the stack always contains the variables for the method invocation currently running. Since variables only store primitives and object references, the actual objects need another place to stay. This is the heap. The heap is pretty much just a big piece of memory where objects and their fields are stored. 
We cannot create objects on the stack. Objects are always created on the heap. 
Whenever a method is invoked a "Stack frame" is given to the method,where method stores its local variable along with its parameter and it also stores there any information which might be required by a particular jvm. to execute it.Heap is a place where object gets memory as a buffer in which instance variable field of that particular class type is created 

We cannnot mark a class private but we can mark its constructor private. Inner classes can be private, protected and static too.

Modified On Jul-13-2015 06:53:26 AM

Don't want to miss updates? Please click the below button!

Follow MindStick