Tuesday, 3 June 2014

Difference between final,finalize and finally in Java

1) final keyword:-

          The final keyword is used to restrict the user. This variable can be applied to variable,method and class.
          
        If you declare the variable as final, you can not change the value of the final variable.(i.e reassignment is not possible for final variables)
     

Example ,

final String name="anil";
name="mahesh";   //it will give compile time error.

        
    If you declare the method as final then you can not override the method in the sub class. Overridden is not possible for the final methods.

Example:-


class Employee{

     public final String details(){                                                 
           return "details";
     }
}

class Manager extends Employee{

    public String details(){                  //will give error                                       
          return "details manager";
    }
}                      


If you declare class as final then you can not extend that class means inheritance is not possible for final classes.
  
Example,


final  class Employee{
        //some statements
}

class Manager extends Employee{          //compilation error,cannot inherit
}


2) finally:

          The finally block is optional and is used in conjunction with a try block, with or without a catch block. Since an exception can interrupt the normal flow of program execution, some resources (such as files, database connections, or network sockets) may remain open if they are not properly closed. The finally block is typically used to release these resources.

          The finally block is executed regardless of whether an exception is thrown or caught. However, there are a few exceptions to this behavior, such as when the JVM is terminated by calling System.exit(), the process is forcibly terminated, or the JVM crashes.


Example,

try{
                                                     
    //some statements

} catch(Exception e){ 
                                                   
    //exception handling block

} finally{

    //e.g close database connection interface,
   //e.g close file resources & so on.....

}
  

3) Finalize() method:-

        Before an object is garbage collected, the JVM may invoke its finalize() method. The original purpose of finalize() was to allow an object to release system resources, such as open files, database connections, or network sockets, before it was garbage collected.

A class can provide its own finalization logic by overriding the finalize() method inherited from the Object class. The method signature is as follows:


        protected void finalize () throws throwable

    This class opens a file when its constructed:

 class OpenFile {
       FileInputStream aFile = null;
       OpenFile(String filename) {
             try {
                  aFile = new FileInputStream(filename);
             } catch (java.io.FileNotFoundException e) {
                  System.err.println("Could not open file " + filename);
             }
       }
 }

    To be well-behaved, the OpenFile class should close the file when its finalized. Here's the finalize() method for the OpenFile class:

protected void finalize () throws throwable {
      if (aFile != null) {
             aFile.close();
             aFile = null;
      }
}

       The finalize() method is declared in the java.lang.Object class. Therefore, when you define a finalize() method in your class, you are overriding the finalize() method inherited from the Object class.

Why not use Finalize() method :-
    There are several reasons why you should avoid using the finalize() method:
  • The execution of finalize() is not guaranteed. The JVM may never invoke it before the object is garbage collected.
  • Unlike constructors, finalize() methods are not invoked in a chain automatically. When a constructor is called, the constructors of all superclasses are invoked implicitly. However, this behavior does not apply to finalize(). If a superclass defines a finalize() method, it must be invoked explicitly by calling super.finalize().
  • Any exception thrown by the finalize() method is ignored by the Garbage Collector (GC) thread. The exception is not propagated to the calling code and is typically not logged, making debugging difficult.
  • The use of finalize() can introduce a significant performance overhead because objects with a finalize() method require additional processing by the garbage collector.


 Related Post:--
1) Exception Handling Interview questions and answers
2) OOP's Concepts in Java and explanation
3) String Interview Questions and Answers
4) How many types of Polymorphism in Java? Explain in brief.
5) Difference between Loose Coupling and Tight Coupling in Java With Examples.

No comments:

Post a Comment