DEVFYI - Developer Resource - FYI

What is the differnce between final, finally and finalize?

Java Interview Questions and Answers (part 1)


(Continued from previous question...)

160. What is the differnce between final, finally and finalize?

final is used for making a class no-subclassable, and making a member variable as a constant which cannot be modified. finally is usuall used to release all the resources utilized inside the try block. All the resources present in the finalize method will be garbage collected whenever GC is called. Though finally and finalize seem to be for a similar task there is an interesting tweak here, usually I prefer finally than finalize unless it is unavoidable. This is because the code in finally block is guranteed of execution irrespective of occurance of exception, while execution of finalize is not guarenteed.finalize method is called by the garbage collector on an object when the garbage collector determines that there are no more references to the object. Presumably the garbage collector will, like its civil servant namesake, visit the heap on a regular basis to clean up resources that are no longer in use. Garbage collection exists to prevent programmers from calling delete. This is a wonderful feature. For example, if you can't call delete, then you can't accidentally call delete twice on the same object. However, removing delete from the language is not the same thing as automatically cleaning up. To add to it, Garbage collection might not ever run. If garbage collection runs at all, and an object is no longer referenced, then that object's finalize will run. Also, across multiple objects, finalize order is not predictable. The correct approach to resource cleanup in Java language programs does not rely on finalize. Instead, you simply write explicit close methods for objects that wrap native resources. If you take this approach, you must document that the close method exists and when it should be called. Callers of the object must then remember to call close when they are finished with a resource.

(Continued on next question...)

Other Interview Questions