final, finally and finalize all are used very frequently in java. This forms the core of java and one of the very prominently asked interview question in java.
Difference between Final, Finally and Finalize
1
|
finally is a block.
|
finalize is a method.
| ||||||||
2
|
2.1) Final variable
final memberVariable
final local variable
final static variable
Final memberVariable of class must be initialized at time of declaration, once initialized final memberVariable cannot be assigned a new value.
Final variables are called constants in java.
If constructor is defined then final memberVariable can be initialized in constructor but once initialized cannot be assigned a new value.
Final local variable can be left uninitialized at time of declaration and can be initialized later, but once initialized cannot be assigned a new value.
Final static variable of class must be initialized at time of declaration or can be initialized in static block, once initialized final static variable cannot be assigned a new value.
If static block is defined then final static variable can be initialized in static block, once initialized final static variable cannot be assigned a new value.
2.2) Final method
Final method cannot be overridden, any attempt to do so will cause compilation error.
Runtime polymorphism is not applicable on final methods because they cannot be inherited.
2.3) Final class
Final class cannot be extended, any attempt to do so will cause compilation error.
|
try-finally block, or
try-catch-finally block.
finally block can can only exist if try or try-catch block is there, finally block can’t be used alone in java.
finally block is not executed in following scenarios >
finally is not executed when System.exit is called.
|
finalize method is called before garbage collection by JVM,
finalize method is called for any cleanup action that may be required before garbage collection.
finalize() method is defined in java.lang.Object
| |||||||
3
|
-
|
finally block can only exist if try or try-catch block is there, finally block can’t be used alone in java.
|
We can force early garbage collection in java by using following methods >
System.gc(); Runtime.getRuntime().gc();
System.runFinalization(); Runtime.getRuntime().runFinalization();
| |||||||
4
|
-
|
finally is always executed irrespective of exception thrown.
|
exception is ignored,
thread is terminated and
object is discarded.
Note : Any exception thrown by the finalize method causes the finalization of this object to be halted, but is otherwise ignored.
| |||||||
5
|
-
|
Currently executing thread calls finally method.
| ||||||||
6
|
final is a keyword in java.
|
finally Is a keyword in java.
|
finalize is not a keyword in java.
|