Understanding final, finally, and finalize() in Java: A Quick Guide

☕ Understanding final, finally, and finalize() in Java These three keywords may sound similar, but they serve completely different purposes in Java! Let’s clear the confusion 👇 🔹 final (Keyword) Used for declaring constants, preventing inheritance, or stopping method overriding. final variable → value can’t be changed final method → can’t be overridden final class → can’t be inherited 👉 Example: final int MAX = 100; 🔹 finally (Block) Used in exception handling to execute important code whether or not an exception occurs. Perfect for closing files, releasing resources, or cleaning up memory. 👉 Example: try { int a = 10 / 0; } catch (Exception e) { System.out.println("Error"); } finally { System.out.println("This will always execute"); } 🔹 finalize() (Method) It’s a method called by the Garbage Collector before an object is destroyed. Used to perform cleanup operations before object removal (though it’s deprecated in newer Java versions). 👉 Example: protected void finalize() { System.out.println("Object destroyed"); } --- 💡 Quick Summary: Keyword Used For Level final Restriction (variable, method, class) Compile-time finally Cleanup code block Runtime finalize() Object cleanup (GC) Runtime --- #Java #Programming #FinalFinallyFinalize #JavaDeveloper #ExceptionHandling #TechLearning #Coding

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories