final vs finally vs finalize in java

In this section we will see the difference between final , finally and finalize .


final

final is a keyword. 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.

class FinalExample{  
public static void main(String[] args){  
final int x=100;  
x=200;//Compile Time Error  
}}  
Compile time error

finally

finally is a block.
Java finally is a block it is always executed irrespective of try and catch.
ava finally-block contains clean-up code such as closing connection, stream etc.


//example of finally-block
class Example {
    public static void main(String arr[]) { 
         System.out.println("Start..");
            try
            {
                System.out.println(50/0);

            }catch(ArithmeticException e)
            {
                System.out.println("Please don' t divide a number by 0");
                e.printStackTrace();
            }   
            finally{
                System.out.println("finally block...cleanup code");
            }

         System.out.println("rest of the code ......");
         System.out.println("End..");
    }        
}
Start..
Please don' t divide a number by 0
java.lang.ArithmeticException: / by zero
	at Example.main(Test.java:8)
finally block...cleanup code
rest of the code ......
End..

finalize

Finalize is a method.
Finalize is used to perform clean up processing just before object is garbage collected.

    class FinalizeExample{  
    protected void finalize(){System.out.println("finalize called");}  
    public static void main(String[] args){  
    FinalizeExample f1=new FinalizeExample();  
    FinalizeExample f2=new FinalizeExample();  
    f1=null;  
    f2=null;  
    System.gc();  
    }}