Friday, 20 June 2014

Difference Between final, finally, finalize In Java

     What is the difference between final, finally and finalize is a common interview question to java developers and also for freshers especially. Even though all are looking related to each other, but they are unrelated. Lets look into the more details.

final : 

    final is a keyword. final can be used to mark a variable as a constant. you can initialize final variable only once. you need to initialize final variable at the time of declaration, otherwise the compiler will throw a compilation error saying " The blank final field may not have been initialized". 

Using final keyword for declaring variable constants :

When applied to a primitive variable, We cannot change value of that variable. 
Eg.: private final String name = "Speaking Cs"; // here name is a constant now, so you can't change 
When applied to a reference variable, we cannot make that reference variable to point to any other object on the heap. But you can change state of the object that is hold by reference variable. 
Eg: private final Map<String,String> obj = new HashMap<String,String>();
obj.put("name","Speaking cs"); // you can change state of the map object, but you can't assign another object
You usually want to use final keyword on static variables that will hold the same value through out the life of your program.

Using final keyword for declaring methods:

When applied to methods, we cannot override the method in it's subclasses. 
Eg: public final String stringNotation() {
         return "$className";
      }
Using final keyword for declaring classes :

When applied to a class, that class cannot be subclassed. Useful , especially when creating Immutable objects. String class is a final class, so jvm not allows to extend in subclasses.
public final class FinalClass {
//do your stuff here
}
public class SubClass extends FinalClass {
// not allowed
}
finally :

    finally is a block. This is an opetional block after the try block or after the catch block. Statements in the finally block will always be executed except if JVM exists from the try block. Calling System.exit(0) will explicitly make jvm to exit. Apart from the exception handling, the finally block is used to write the clean up code. Even in case of accidentally by passed by a return, continue, break, finally block will be executed by the jvm. Putting clean up code is always a good programming practice, even when no exceptions are anticipated. 
Eg: InputStream fis ;
      try {
        fis = new FileInputStream("abc.txt");
        // do remaining here 
      } catch(FileNotFoundException fne) {
       // handle exception 
     } finally {
      if(fis != null) {
      fis.close()
      // this block will get executed by jvm automatically in case of any exception.
      }
Java 7 , has a new try with resources statement that you can use to automatically close resources that explicitly or implicitly implement java.io.Closeable or Java.lang.AutoCloseable.

finalize : 

     finalize is a protected method in the class "Object", this method can be overridden by other classes. Before the storage for an object is reclaimed by the garbage collector. the JVM will invoke the finalize method of that object. finalize provide a chance to free up resources that cannot be freed automatically by an automatic storage manager. finally should not be used to release non-memory resources like file handlers, sockets, database connections etc because java has only a finite number of these resources and the garbage collection is going to release these non - memory resources through finalize method only when the objects are unreachable. 

You rarely need to override it. Unlike constructors, finalizers donot automatically invoke finalize method for the super class, you need to invoke super class finalize method explicitly using super.finalize() snippet. 
protected void finalize() throws Throwable {
// free resources (e.g unallocate memory) 
super.finalize();
}

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.