A2oz

How to Print How Many Objects are Created in Java?

Published in Java Programming 2 mins read

You can track the number of objects created in Java using a static counter variable within your class. Here's how:

  1. Declare a Static Counter:

    • Inside your class, declare a static variable of type int to keep track of the object count.
    • Initialize it to 0.
    public class MyClass {
        private static int objectCount = 0;
  2. Increment the Counter in the Constructor:

    • In the class's constructor, increment the objectCount variable by 1.
    public MyClass() {
        objectCount++;
    }
  3. Create a Getter Method:

    • Create a static method to return the current value of objectCount.
    public static int getObjectCount() {
        return objectCount;
    }
  4. Print the Object Count:

    • Call the getObjectCount() method to retrieve the object count and print it.
    public static void main(String[] args) {
        MyClass obj1 = new MyClass();
        MyClass obj2 = new MyClass();
        System.out.println("Number of objects created: " + MyClass.getObjectCount()); 
    }

Example:

public class MyClass {
    private static int objectCount = 0;

    public MyClass() {
        objectCount++;
    }

    public static int getObjectCount() {
        return objectCount;
    }

    public static void main(String[] args) {
        MyClass obj1 = new MyClass();
        MyClass obj2 = new MyClass();
        System.out.println("Number of objects created: " + MyClass.getObjectCount()); // Output: 2
    }
}

This approach provides a simple way to track the number of objects created for a specific class in your Java program.

Related Articles