What is difference between "finalise" and "finally" methods ?
Loading
What is difference between "finalise" and "finally" methods ?
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Amit MohantyPosted Aug 1, 2022, 10:50 AM
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 HawaldarPosted Aug 1, 2022, 10:23 AM
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.