Monday, April 4, 2016

Final Vs Finally Vs Finalize()



This is very important interview question. Lets get one by one.

Final

Final is a non access modifier that can be used with a variables, methods and also classes.

Final variables
    • Final variables cannot be changed, because they are constants. 
    • Look at the following code, it won't compile.

public class Fruits {

   public static void main(String[] args) {
       final int MAX_DIS = 5;
       MAX_DIS = 10;
  
       System.out.println(MAX_DIS);
   }
}


Final methods
    • Final methods cannot be overridden. 
    • Following code won't compile.

public class Fruits {
   final void eat() { }
}

class Apple extends Fruits {
   void eat() { }
}


Final classes
    • Final classes cannot be extended.
    • Following code won't compile.

public final class Fruits {

}

class Apple extends Fruits {

}


Finally

  • This is always associated with try-catch block.
  • It is normally used to handle any clean up codes like closing a file, closing a database to prevent resource leak.
  • This finally block runs every time either exception happen or not.
  • Look at the following example.

public class FinallyBlockDemo {

   public static void main(String args[]) {

       double num1=0, num2=0;
       Scanner scn = new Scanner(System.in);

       try{
           System.out.print("Enter number one: ");
           num1 = scn.nextInt();

           System.out.print("Enter number two: ");
           num2 = scn.nextInt();

           double div = num1 + num2;
           System.out.println("Answer is : " + div);
   
       }catch(InputMismatchException e){
            System.out.println("Please enter number only.");

       }finally{
            System.out.println("Service stopped.");

       }
   }
}


Finalize() 

  • This method is presented in Object class (Java.lang.Object.finalize())
  • This is called by the Garbage collector just before destroying any object.
  • If it determines any object without a reference, it calls this method anytime. 
  • This is used to perform clean up activities related to any object without reference.
  • This cleanup activities means, if the object is associated with any database connection, finalize() method is used to disconnect that connection.