This page topics close

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.

    Example)
    drag_handle
     class FinalExample{  
    public static void main(String[] args){  
    final int x=100;  
    x=200;//Compile Time Error  
    }}  
    Output:
    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)
    drag_handle
     
    //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..");
        }        
    }
    
    Output:
    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.

    Example)
    drag_handle
         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();  
        }}  
    Output:
     

What next?

The next topic is Custom Exception in java

Share this page