🍀Finalization

🚨 The Final Frontier of Java Keywords 🚨

The dynamic trio of final, finally, and finalize() serve unique purposes though they sound similar! Let's break it down:

The Immutable final 🔒

📌 Rules of final:

final int MAX_VALUE = 100; // Constant 

final public void print() { // Method 
   //...
}

final class Car { // Class
   //... 
}
  • Declares immutable properties ❌🔀

  • Prevent overriding in subclasses 🚫

  • Commonly used for constants 📏

Key Benefits:

  • Avoid unintended changes 🙅‍♂️

  • Enforce architectural rules 👮

  • Improved understandability 💡

The Unstoppable finally 🚥

🧐 Purpose of finally:

try {
  // Exception prone code
}
catch (Exception e) {
  // Handle exception
}
finally {
  // Always executes after try/catch ✅
} 
  • Guaranteed execution before method exit 🏁

  • Commonly closes resources 🗑️

Why use finally?

  • Release external resources 🖇️

  • Restore program state 💾

  • Critical code that must run ✅

The Destructor finalize() 👋

🔚 When finalize() gets called:

protected void finalize() { 
//Cleanup before garbage collection
  super.finalize(); 
}
  • Just before object is garbage collected 🗑️

  • Rarely used nowadays

  • try-finally preferred

Downsides offinalize():

  • Not guaranteed to run 🤷‍♂️

  • Causes performance issues 🔥

  • Anti-pattern in most cases ❌

So while they sound similar, each handles unique responsibilities!

Last updated