Java - Interview Questions and Answers on Final, Finally and Finalize

Q1.  What is the difference between final, finally and finalize() ?

Ans. final - constant variable, restricting method overloading, restricting class subclassing.

finally - handles exception. The finally block is optional and provides a mechanism to clean up regardless of what happens within the try block. Use the finally block to close files or to release
other system resources like database connections, statements etc.

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. 

Q2.  What is a final method ?

Ans. Its a method which cannot be overridden. Compiler throws an error if we try to override a method which has been declared final in the parent class.

Q3.  What is a final variable ?

Ans. Final variable is a constant variable. Variable value can't be changed after instantiation.

Q4. What is a final Class ?

Ans. Class that cannot be subclassed.

Q5.  Does Declaring an object "final" makes it immutable ?

Ans. Only declaring primitive types as final makes them immutable. Making objects final means that the object handler cannot be used to target some other object but the object is still mutable.

Q6.  How can we make sure that a code segment gets executed even in case of uncatched exceptions ?

Ans. By putting it within finally.

Q7.  What is a finalize method ?

Ans. finalize() method is called just before an object is destroyed.

Q8.  Should we override finalize method ?

Ans. Finalize is used by Java for Garbage collection. It should not be done as we should leave the Garbage Collection to Java itself.

Q9.  Is it necessary that each try block to be followed by catch block ? 

Ans. It should be followed by either catch or finally block.

Q10.  Can finally block be used without catch ?

Ans. Yes but should follow "try" block then.