Difference Between final, finally And finalize In Java | Interview Question Explained
final - keyword
finally - block
finalize() - method
final:
used to apply restrictions on class, method and variable.
- final variable => value can not be changed
- final method => you cannot override it
- final class => you cannot extend it
Example:
class FinalExample{
public static void main(String[] args){
final int x=10;
x=200; //Compile Time Error
}}
finally:
- used with try-catch
- after try-catch block but before control transfers back to its origin
- executes whether exception occurs or not
class FinallyExample{
public static void main(String[] args){
try{
int x=300;
}catch(Exception e){System.out.println(e);}
finally {System.out.println("finally block is executed");}
}}
Garbage => unreferenced Object
finalize:
- invoked each time before garbage collection
- System.gc() => used to invoke garbage collection
- after try-catch block but before control transfers back to its origin
- executes whether exception occurs or not
Example:
class C1{
public static void main(String[] args){
C1 a=new C1();
C1 b=new C1();
a=null;
b=null;
System.gc();
}
public void finalize(){
System.out.println("GC");
}
}
Output: GC GC (2 times as 2 objects)