Java Execution Order: A Common Mistake

💥 Java Execution Order That Most People Miss! When inheritance comes into play, Java executes things in a very specific order ⚙️ And if you get it wrong — interview me “hmm interesting…” bolke confuse kar dete hain 😅 🧩 The Order is Always: Parent static → Child static → Parent instance → Parent constructor → Child instance → Child constructor For example: class Parent {   static {     System.out.println("Parent static block");   }   {     System.out.println("Parent instance block");   }   Parent() {     System.out.println("Parent constructor");   } } class Child extends Parent {   static {     System.out.println("Child static block");   }   {     System.out.println("Child instance block");   }   Child() {     System.out.println("Child constructor");   }   public static void main(String[] args) {     new Child();   } } Output: Parent static block Child static block Parent instance block Parent constructor Child instance block Child constructor 💡 Why this order? * Static blocks → loaded once when class is first loaded into memory. * Instance blocks → run every time object is created (before constructor). * Constructors → run after instance initialization. ⚔️ Quick Tip: Even if you create multiple Child objects, static blocks run only once, but instance blocks + constructors run every time. 🚀 If you found this helpful, 👉 Follow me for more Java tips, interview concepts, and daily developer insights! #Java #CoreJava #InterviewPreparation #JavaTips #CodeWithAniket #OOPsConcepts #JavaDeveloper

To view or add a comment, sign in

Explore content categories