AdSense

AdSense3

Wednesday, 17 September 2014

Difference between final, finally and finalize

There are many differences between final, finally and finalize. A list of differences between final, finally and finalize are given below:

No.finalfinallyfinalize
1)Final is used to apply restrictions on class, method and variable. Final class can't be inherited, final method can't be overridden and final variable value can't be changed.Finally is used to place important code, it will be executed whether exception is handled or not.Finalize is used to perform clean up processing just before object is garbage collected.
2)Final is a keyword.Finally is a block.Finalize is a method.

Java final example

  1. class FinalExample{  
  2. public static void main(String[] args){  
  3. final int x=100;  
  4. x=200;//Compile Time Error  
  5. }}  

Java finally example

  1. class FinallyExample{  
  2. public static void main(String[] args){  
  3. try{  
  4. int x=300;  
  5. }catch(Exception e){System.out.println(e);}  
  6. finally{System.out.println("finally block is executed");}  
  7. }}  

Java finalize example

  1. class FinalizeExample{  
  2. public void finalize(){System.out.println("finalize called");}  
  3. public static void main(String[] args){  
  4. FinalizeExample f1=new FinalizeExample();  
  5. FinalizeExample f2=new FinalizeExample();  
  6. f1=null;  
  7. f2=null;  
  8. System.gc();  
  9. }}  

1 comment: