1.

What is the difference between final, finalize and finally?

Answer»

There are quite a few differences between final, finalize and finally.

  • final is a KEYWORD which is used to curtail the class, method or variable on which it is applied. A final class cannot be inherited by a subclass, a method declared as final cannot be overridden or a variable declared as final cannot be updated.
  • finalize is a method which is used to clean up the processing before the garbage collection in java. It is called by the garbage collector of an OBJECT when there are no further references to that object.
  • finally is a block which is a part of the try-catch-finally flow block and is used to execute code irrespective of the handling of exceptions in the try and catch blocks.

The finalize, unlike final and finally is not a reserved keyword in Java. The finalize method can be invoked explicitly which leads to it being executed as a normal method call and wouldn’t lead to destruction of the object.

Let us see a program which violates the use of the final keyword:

public class Example {      public STATIC void main(String[] args)    {            final int x=1;              x++;     } }

The program will generate a compile time error as a final variable can’t be updated:

$javac Example.java Example.java:6: error: cannot assign a value to final variable x            x++;//Compile Time Error              ^ 1 error

 Now let us look at the use of finally keyword in Java:

public class Example {    public static void main(String[] args)    {        try        {         System.out.println("In try block");         int a=1/0;        }        catch(ArithmeticException e)        {            System.out.println("Exception Caught");        }        finally        {            System.out.println("In finally block");        }    } }

The program will give the following output:

$javac Example.java $java Example In try block Exception Caught In finally block

Now let us look at the overriding of finalize method in Java:

public class Example {    public static void main(String[] args)    {        String str = NEW String("Example");        str = null;        System.gc(); // prompts the JVM to call the Garbage Collector        System.out.println("End of main method");    }    public void finalize()    {        System.out.println("This is the finalize method");    } }

The output is as follows:

$javac Example.java $java Example End of main method


Discussion

No Comment Found