Java final vs finally vs finalize() - Key differences and usage

🔥 final vs finally vs finalize() — Don’t mix them up! These 3 Java terms look similar but serve completely different purposes. Let’s break it down 👇 --- 🟢 1. final (Keyword) ✔ Used for constants & immutability ✔ Prevents modification / overriding 💡 Examples: final int MAX_VALUE = 100; // constant final void show() {} // cannot override final class A {} // cannot extend 👉 Think: Restriction / Protection --- 🔵 2. finally (Block) ✔ Used in exception handling ✔ Always executes (even if exception occurs) 💡 Example: try { int x = 10 / 0; } catch (Exception e) { System.out.println("Error"); } finally { System.out.println("Always runs"); } 👉 Think: Cleanup (DB, files, connections) --- 🔴 3. finalize() (Method) ⚠️ ✔ Called by Garbage Collector before object destruction ❌ Deprecated since Java 9 💡 Example: @Override protected void finalize() throws Throwable { System.out.println("Cleanup"); } 👉 Not reliable ❌ 👉 Use try-with-resources instead ✅ --- ⚡ Key Differences Feature final finally finalize() Type Keyword Block Method Purpose Restrict changes Cleanup in exceptions Cleanup before GC Usage Variables, methods, classes try-catch Object lifecycle Status ✅ Active ✅ Active ❌ Deprecated --- 🎯 Quick Trick to Remember 👉 final = no change allowed 👉 finally = always executes 👉 finalize() = forgotten (deprecated) 😄 --- 💬 Which one confused you the most earlier? Let me know 👇 #Java #SpringBoot #BackendDevelopment #Programming #JavaConcepts #InterviewPrep 🚀

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories