stack and heap in java

Total Post:17

 1282  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??
  1. Post:397

    Re: stack and heap in java

    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 Apr-10-2018 01:18:04 AM