title: How to check the number of objects created in heap memory?
body: <p>I want to see how many objects are created by Java when I run my program. </p>
  
  <p>My intention is if I use the code <code>String s = new String("Hi");</code> I want to see how many objects Java will create. Later I want to try with <code>String news = "Hi";</code></p>
  
  <p>This is my sample program:</p>
  
  <pre><code>import java.util.Scanner;
  
  public class Test { 
      public static void main(String[] args) {
          String str = new String("Hi");
          Scanner s = new Scanner(System.in);
          s.nextLine();
      }
  }
  </code></pre>
  
  <p>I am using <code>Scanner</code> just to avoid the program to terminate.</p>
  
  <p>I have gone through this SO post <a href="https://stackoverflow.com/questions/2262620/how-to-find-the-number-of-objects-in-the-heap">How to find the number of objects in the heap</a> and tried to use <code>jvisualvm</code>, but the tool is not giving the count of my objects created in my class. I also do not understand how to get the actual count of objects based on below image.</p>
  
  <p><a href="https://i.stack.imgur.com/ZPQCj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZPQCj.png" alt="enter image description here"></a> </p>
  
  <p>When I tried to use the command <code>jmap -heap &lt;pid&gt;</code> then I get below error:</p>
  
  <blockquote>
    <p>Attaching to process ID 15101, please wait... Error attaching to
    process: sun.jvm.hotspot.debugger.DebuggerException: Can't attach to
    the process</p>
  </blockquote>
  
  <p>If I use eclipse Debug as option, then I see that it is not the correct way to find out the number of objects that are being created.</p>