Difference between final, finally & finalize keywords in java is :
| S.No | final | finally | finalize |
|---|---|---|---|
| 1 | 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. | Finally is used to place important code, it will be executed whether exception is handled or not. | Finalize is used to perform clean up processing just before object is garbage collected. |
| 2 | Final is a keyword. | Finally is a block. | Finalize is a method. |
Examples :
1. Final keyword :
class FinalKeywordExample {
public static void main(String[] args) {
final int x = 10;
x = 20;// Compile Time Error
}
}
2. Finally block :
class FinallyKeywordExample {
public static void main(String[] args) {
try {
int x = 30;
} catch (Exception e) {
System.out.println(e);
} finally {
System.out.println("finally block is executed"); // this gets printed
}
}
}
3. Finalize method :
class FinalizeKeywordExample {
public void finalize() {
System.out.println("finalize called");
}
public static void main(String[] args) {
FinalizeKeywordExample f1 = new FinalizeKeywordExample();
FinalizeKeywordExample f2 = new FinalizeKeywordExample();
f1 = null;
f2 = null;
System.gc();
}
}
Summary
So here we are, we hope now you got to know difference between final, finally and finalize keyword in java.
We tried our best to simplify the explanation, if you feel any difference or you need help in understanding any such thing, then feel free to contact us through email and subscribe to ProgrammerToday.