Difference between final, finally, finalize?

Though final, finally, and finalize sound similar in Java, they each serve very different purposes. Here’s a clear breakdown:

🔒 final – The Constant Keyword

Used as a modifier for variables, methods, and classes.

  • Variables: Makes the value constant (can’t be changed).
  • Methods: Prevents overriding in subclasses.
  • Classes: Prevents inheritance (cannot be subclassed).

🔁 finally – Always Executes

Used in exception handling to ensure a block of code runs no matter what, whether or not an exception occurs.

Think: cleanup duty—like closing files, releasing connections, etc.

🧹 finalize() – Legacy Cleanup Method (Not Recommended)

A method that Java calls before an object is garbage collected.

  • Used to free up resources before an object is removed.
  • Rarely used now because it’s unpredictable and mostly obsolete. Java recommends alternatives like try-with-resources.

🧠 Quick Recap Table

KeywordWhat is it?Used for…
finalModifierConstants, prevent override/inherit
finallyCode blockRun cleanup code after try/catch
finalizeMethodLegacy cleanup before garbage collect

Leave a Reply

Your email address will not be published. Required fields are marked *