Program to count number of object created in java

Sometime in the interview, you may be asked to write a program to count a number of objects created in the application. Let’s see a java program which illustrates how many numbers of objects has been created. Since instance block and constructor will invoke at the time of object creation, we can use further this logic to write a program.

First method- Using instance block.

package countnumberofobject;

public class CountObjectExample {
	
	static int countObject = 0;
	
	//using instance block since instance block will invoke at object creation
	
	{
		countObject++;
	}
public static void main(String[] args) {
	CountObjectExample object1 = new CountObjectExample();
	CountObjectExample object2 = new CountObjectExample();
	CountObjectExample object3 = new CountObjectExample();
	CountObjectExample object4 = new CountObjectExample();
	CountObjectExample object5 = new CountObjectExample();
	CountObjectExample object6 = new CountObjectExample();
	CountObjectExample object7 = new CountObjectExample();
	
	System.out.println("number of object created is "+countObject);
}
}

Output is – number of object created is 7

 

Second method –

package countnumberofobject;

public class CountObjectExample2 {
	
	static int countObject = 0;
	
	//constructor will invoke at object creation
	CountObjectExample2(){
		countObject++;
	}
	
public static void main(String[] args) {
	CountObjectExample2 object1 = new CountObjectExample2();
	CountObjectExample2 object2 = new CountObjectExample2();
	CountObjectExample2 object3 = new CountObjectExample2();
	CountObjectExample2 object4 = new CountObjectExample2();
	CountObjectExample2 object5 = new CountObjectExample2();
	CountObjectExample2 object6 = new CountObjectExample2();
	CountObjectExample2 object7 = new CountObjectExample2();
	
	System.out.println("number of object created is "+countObject);
}
}

Output is – number of object created is 7