Java Interview Question – Difference between final, finally and finalize
The difference between final, finally and finalize method is very frequently asked in Java interviews and hence every candidate should be aware of the answer to this question. While answering a question make sure not to go in to too much detail as it will make the discussion monotonous. Try explaining the difference between the three keywords in brief and let the interviewer asked any kind of detail he wants to ask.
The final variable is used with variables, methods and classes.
When used with primitive variables, changing the value of those variables is not allowed. Moreover, final variable has to be assigned a value before it can be used for first-time.
On the other hand the final keyword each used it reference variables, these variables can not be changed referred to a different object than the one to which they were referring to during initialization.
It is important to note here that though the final reference variables cannot refer to a different object but the object they are pointing to can be modified. A common usage of final variables is for defining constants and for defining variables in immutable classes.
When the final keyword is used with methods then it means that those methods cannot be overridden by the subclass. This also means that the subclass has to use the same code as defined in the super class final method which is inherited by the subclass.
When the final keyword is used with the class definition then it means that the class cannot be extended by any other class. The purpose of having such a class is to define behavior with should not be extended or modified in any manner. To implement immutability in a class, it should be marked as final. For example, the string classes marked as final in JDK.
The finally block is used to execute a piece of code which should always be executed irrespective of whether an exception has occurred or not. The finally block usually contains cleanup code like cleanup of database connections or file handlers. Read more on finally.
The finalize method is used in respect of garbage collector in Java. This method is declared in the object class and hence all the classes in Java inherit this method. However any class can override the finalize method and add some custom code. The finalize method is invoked by the garbage collector before an object is going to be garbage collected.
Thus if you have a requirement where some piece of code should always be executed before object is garbage collected then finalize is the place where you should be adding that code. It is important to note here that, you should not try to execute any kind of code page this allows the object in context to be garbage collected as it can result in unexpected behavior.