Difference between final, finally and finalize in Java — Java Technical Interview Questions & Answers
Difference between final, finally and finalize in Java
Difference between final, finally and finalize in Java
- final locks: variable cannot reassign, method cannot override, class cannot extend. finally is the try cleanup block. finalize is an old GC callback — do not use it in new code.
- Viva loves mixing these three. Answer in three short lines. Don’t write one mixed paragraph.
- finally is for close(). final is for MAX = 100 or a locked design. finalize is history.
- Let's take this on the board with one tiny Main class — no extra files. Output: Asha scored 72 then Pass. Real Main. Swap marks/name to show one idea from Difference between final, finally and finalize in Java. Start from main, go line by line, and stop at each print. That output is the proof for Difference between final, finally and finalize.
Technical Interview Tip: Three lines: final locks, finally cleans up after try, finalize is old GC — don’t use it.
Code Examples for Difference between final, finally and finalize in Java
Example
// Difference
public class Main {
public static void main(String[] args) {
int marks = 72;
String name = "Asha";
System.out.println(name + " scored " + marks);
if (marks >= 40) System.out.println("Pass");
}
}Output: Asha scored 72 then Pass. Real Main. Swap marks/name to show one idea from Difference between final, finally and finalize in Java.
How to Explain Difference between final, finally and finalize in Java to an Interviewer
What is final?
Lock variable / method / class
What is finally?
Cleanup after try
Should you use finalize?
No Old GC hook