InterviewSolution
| 1. |
What is the difference between final, finalize and finally? |
|
Answer» There are quite a few differences between final, finalize and finally.
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 errorNow 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 blockNow 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 |
|