title: Java stack and heap memory management
body: <p>I want to know how the memory is being allocated in the following program:</p>
  
  <pre><code>public class MemoryClass {
  
      public static void main(final String[] args) {
          int i = 0;
          MemoryClass memoryClass = new MemoryClass();
          memoryClass.myMethod(memoryClass);
      }
  
      private void myMethod(final Object obj) {
          int i = 1;
          String s = "HelloWorld!";
  
      }
  
  }
  </code></pre>
  
  <p>Now, as far as my understanding goes, the following diagram describes how the memory allocation takes place:<br>
  <a href="https://i.stack.imgur.com/4Ttvc.png" rel="noreferrer"><img src="https://i.stack.imgur.com/4Ttvc.png" alt="Basic runtime memory allocation"></a></p>
  
  <p><br>
  In the above diagram, <strong>memory</strong>,<strong>obj</strong> and <strong>s</strong>, which are in the stack memory, are actually the references to their "<strong>actual objects</strong>" which are placed inside the heap memory.
  <br>
  Here is the set of questions that come to my mind:</p>
  
  <ol>
  <li>Where are the methods of <strong>s</strong> stored?</li>
  <li>Had I created another object of <code>MemoryClass</code> inside <code>myMethod</code>, would JVM allocate memory for the same methods again inside the stack memory?</li>
  <li>Would JVM free the memory allocated to <code>myMethod</code> as soon as it's execution is completed, if so, how would it manage the situation mentioned in question 2(<em>only applicable if JVM allocates memory multiple times to the same method</em>).</li>
  <li>What would have been the case, if I had only declared <strong>s</strong> and did not initialize it, would JVM still allocate memory to all the methods of <code>java.lang.String</code> class,if so,why?</li>
  </ol>