Monu Alam’s Post

🔥 final vs finally vs finalize — Clear & Simple Explanation 🔹 final (keyword): • final variable → value cannot be changed once assigned • final method → cannot be overridden in a subclass • final class → cannot be inherited (no subclass can be created) • Example: `final int x = 10;` 🔹 finally (block): • Always executes after try-catch (whether exception occurs or not) • Used for cleanup tasks like closing DB connections, files, etc. • Executes even if a return statement is present in try or catch • Example: `finally { conn.close(); }` 🔹 finalize() (method): • A method of Object class, called by Garbage Collector before object is destroyed • Used earlier for cleanup, but NOT reliable for critical operations • Deprecated since Java 9 ⚠️ • Avoid using it — use try-with-resources or explicit cleanup instead ✅ #Java #SpringBoot #JavaInterview #JavaDeveloper #BackendDeveloper

  • table

Why can’t we call finalize() ourselves? finalize() is meant to be called by the Garbage Collector, not by developers. Even if you call it manually, it works like a normal method and does NOT guarantee proper cleanup. Also, Garbage Collection timing is unpredictable, so relying on finalize() can cause resource leaks. That’s why it’s deprecated. finalize() may not run at all before the program ends, and in some cases, it can even be skipped entirely by the JVM. That’s why it’s considered unreliable and unsafe for critical cleanup.

Why was finally block introduced? finally block was introduced to solve a major problem resource leakage. If an exception occurs, cleanup code (like closing DB connections, files, etc.) might get skipped. finally ensures that cleanup code runs whether an exception occurs or not. ⚠️ Important Note: It may feel like finally always runs, but there are exceptions. If System.exit() is called before finally executes, the JVM shuts down immediately and finally will NOT run. Even if there is a return statement inside try or catch, finally still executes before the method actually returns which makes it very powerful for ensuring cleanup.

final finally finalize and AI

Like
Reply
See more comments

To view or add a comment, sign in

Explore content categories