Home » Core Java » Difference between final, finally and finalize

Difference between final, finally and finalize

Difference between final, finally and finalize is being asked in almost every java interview rounds now-a-days.

Whether you are a beginner or intermediate or expert in Java ,you can expert this question in interview rounds.Let us see the the comparison first and then we will see some programs related to  final, finally and finalize

final:

1. final is a keyword.
2. If a variable is declared as final then it should be initialized only once while declaring and its value cannot be changed later .
3. If a class is declared is  final ,then it can not be extended by any sub class.
4. If a method is declared as final,then it can not be overridden.

finally:
1. finally is a keyword with  a block in its syntax.
2. finally block always executes if the try block is present.Even if your program throws exception finally block will execute.If you  write System.exit() in try block or catch block ,then finally block will not execute.
3. finally can bypass return ,break or continue and can still execute.
4. Resource clean up,connection close ,stream close etc. code should be put in finally block.

finalize:
1. finalize is a method.
2. Just before an object is garbage collected.When System.gc() is invoked then finalize() method may be(not always)  called.
4. Resource clean up code can be put in finalize() method.

Final example ::

final variable ::


final class ::

final method ::

Finally Example ::


Finalize Example ::


Leave a comment

Your email address will not be published. Required fields are marked *

1 + ten =