The difference between final, finally, and finalize


final:


The final is a modifier, it is applicable for classes, methods, and variables
If we declared as final then we can not extend that class i.e. inheritance it not possible for final classes.
If a method is final then that method can not override in child classes.
If a variable declared as final then we can not reassign it.


//can not inherit
public final class Test {
       //can not override in child class
       final void message(){
             
       }
       public static void main(String[] args) {
              final int id=101;
              id=102;
       // compile time error: The final local variable id cannot be assigned
       }     
}


finally block:


The finally is block, it is used along with try and catch blocks to maintain the cleanup activities and place the important code because it is executed always whether exception handle or not.


public class Test {       
       public static void main(String[] args) {
              try {
                     int i=10;
              }
              catch (Exception e) {
                     System.out.println("Handling code "+e);
              }
              finally{
                     System.out.println("cleanup activities, execute always");
              }
       }     
}


finalize method:


The finalize() method is available in Object class and it is called by Garbage Collector to cleanup the activities of the object.

protected void finalize()


public class Test {
       @Override
       protected void finalize() throws Throwable {
              System.out.println("finalize called");
       }
       public static void main(String[] args) {
              Test obj1=new Test();
              Test obj2=new Test();
              obj1=null; //eligible GC
              obj2=null; //eligible GC                
              System.gc(); //finalize() call
              System.out.println("main block");
       }     
}


final vs finally vs finalize


final
finally
finalize
modifier         
block
method
Applicable for classes,  methods, and variables
Associate with try and catch blocks
Called by garbage collector
public final class Test
final void message()
final int id=101;
try{  
}
catch(){     
}
finally{     
}
System.gc
or
Runtime r = Runtime.getRuntime();
r.gc();
We can not extend final class, can not override final methods, and can not reassign variables
finally block is used to place important code and cleanup activities
finalize() method is used to clean up the activities of object

Whatever the code or connections(like database, network) open in the try block that code cleanup or close in finally block
Whatever the connections(like database, network) associated with the object even that object doesn't have a reference then finalize() method cleanup that connections or close.

finally block is related to try block
finalize() is related to the object




No comments:

Post a Comment