๐Ÿ€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