How to count objects created in Java with a simple trick

💡 Tiny Java Trick, Big Lesson 💥 Ever wondered how to count how many objects your class actually creates? 👇 class Test {   private static int objectCount = 0; // shared across all objects 💡   public Test() {     objectCount++; // increments whenever a new object is created   }   public static int getObjectCount() {     return objectCount;   }   public static void main(String[] args) {     new Test();     new Test();     new Test();     System.out.println("Objects created: " + Test.getObjectCount());   } } 🖥️ Output: Objects created: 3 ⚙️ What’s happening here? static → belongs to the class, not individual objects Constructor → runs each time a new object is created Together → you can easily track how many instances exist 💭 Why it matters: This tiny concept is the foundation for: ✅ Singleton patterns ✅ Page Object lifecycle in automation frameworks ✅ Memory-efficient test design ✨ Sometimes the most basic Java tricks teach the most advanced lessons about memory and design. 💬 What’s one small Java concept that gave you a big “Aha!” moment? Drop it below 👇 #Java #Coding #AutomationTesting #Selenium #TestAutomation #DeveloperLife #LearningEveryday

To view or add a comment, sign in

Explore content categories