Java Interview Question: final, finally, and finalize() Explained

🚀 Java Interview Question: Difference between "final", "finally", and "finalize()" This is one of the most frequently asked Java interview questions, especially for freshers and mid-level developers/QA Let’s break it down simply 👇 🔹 1️⃣ "final" (Keyword) "final" is used to restrict modification. It can be applied to: • Variable → Value cannot be changed (constant) • Method → Cannot be overridden • Class → Cannot be inherited Example: final int x = 10; x = 20; // ❌ Compile-time error Example with method: class Parent { final void show() { System.out.println("Final method"); } } --- 🔹 2️⃣ "finally" (Block) "finally" is used in exception handling. The code inside "finally" always executes, whether an exception occurs or not. Commonly used for: ✔ Closing database connections ✔ Closing files ✔ Cleaning resources Example: try { int a = 10 / 0; } catch(Exception e) { System.out.println("Exception occurred"); } finally { System.out.println("Always executed"); } --- 🔹 3️⃣ "finalize()" (Method) "finalize()" is a method of the Object class. It is called by the Garbage Collector before destroying an object to perform cleanup activities. Example: protected void finalize() { System.out.println("Object is garbage collected"); } ⚠️ Note: "finalize()" is deprecated in modern Java and should not be relied upon. --- 📊 Quick Comparison Feature| final| finally| finalize() Type| Keyword| Block| Method Used For| Restrict modification| Exception handling cleanup| Garbage collection cleanup Applies To| Variables, methods, classes| try-catch block| Object class --- 💡 Interview Tip: Remember this simple line: 👉 final → restriction 👉 finally → exception cleanup 👉 finalize() → garbage collection --- If you found this helpful, follow for more Java interview questions & backend development tips. 💻🔥 #Java #JavaInterview #Programming #SoftwareDevelopment #CodingInterview #JavaDeveloper

Prati T. Great explanation, Prati 👏 The final vs finally vs finalize() confusion is very common—this makes it super clear. 👍

To view or add a comment, sign in

Explore content categories