final , finally and finalize difference ?

By | May 26, 2014

This a common java interview question . All these keywords have different use  this is what you are supposed to tell if this question is asked to you in you interview.

final

    final keyword has different meaning in different contexts.

  • Final class
    A class that cannot be subclassed/extended
  • Final method
    A final method cannot be overridden by subclasses
  • Final variable
    If an instance variable is marked final, it can be initialized only once and cannot be reinitialized. For primitive type variables, the value assigned once cannot be changed. For reference variables, the variable cannot be reassigned to refer to a different object. However, the final reference variable allows the object it refers to be modified. In Java a constant is defined my marking the variable static and final.

finally

finally is a block which which we use with try- catch block the catch block may or may not be there .
The finally block will be executed irrespective of whether the catch block is executed or not. Doesn’t matter whether an exception came or not.Generally it is used to de allocate resources or for the things like closing opened streams.

finalize

finalize is a method used for garbage collection. finalize() method will be invoked just before the Object is garbage collected. It will be called automatically by the JVM on the basis of resource reallocating. Even programmers can call finalize method by using System.gc().

Leave a Reply

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