Loading
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Amit MohantyRank #112 · 20K reputationPosted Aug 1, 2022, 6:50 AM EDT
Finalize is a method of Object class. It is invoked before an object is discarded by the garbage collector, used to free unmanaged resources like database connections etc. The method finalize() is for unmanaged resources.
Rajanikant HawaldarRank #110 · 20.2K reputationPosted Aug 1, 2022, 6:23 AM EDT
finalize() – method helps in garbage collection. A method that is invoked before an object is discarded by the garbage collector, allowing it to clean up its state.
public class Demo{
public static void main(String[] args){
Demo d = new Demo();
d = null;
System.gc();
System.out.println("Grabage collection");
}
protected void finalize(){
System.out.println("Finalize()");
}
}
Output: Garbage collection
Finalize()
Finally – The finally block always executes when the try block exits, except System.exit(0) call. This ensures that the finally block is executed even if an unexpected exception occurs.
public class Demo{
public static void main(String[] args){
try{
System.out.println("Try block");
int value = 5/0;
System.out.println(value);
}
catch (ArithmeticException ex){
System.out.println("Exception");
System.out.println(ex);
}
finally{
System.out.println("Finally block");
}
}
}
Output : Try block
Exception
Exception as / by zero
Finally block.