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
final can be applied to variable, method and class in java.
finally is a block.
finalize is a method.
2.1) Final variable
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 or try-catch block can be followed by finally block >
try-finally block, or
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.
if in case JVM crashes because of some java.util.Error.
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
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 >
finally is always executed irrespective of exception thrown.
If any uncaught exception is thrown inside finalize method -
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.
Currently executing thread calls finally method.
final is a keyword in java.
finally Is a keyword in java.
finalize is not a keyword in java.