In this article, we will discuss the difference between final, finally and finalize in detail with example
This is one of the top interview question for Java fresher’s and at junior level to check the knowledge of core Java concepts
First of all, final & finally & finalize is used in different scenarios and also they aren’t similar in any context like
- final is a keyword used for restricting further alteration in inheritance
- finally is a block & it is associated with try-catch block in exception handling for clean-up activity
- finalize() is a method associated with garbage collector to de-allocate resources associated with the Object
Let us discuss each one in detail with example
1. final keyword:
- final is keyword or modifier
- applicable only for variable, method & classes
- variable declared as final can’t be changed or re-assigned once it is initialized
- method declared as final can’t be overridden in the sub-class (inheriting-class or extending-class)
- class declared as final can’t be extended i.e.; inherited further (or sub-class’d)
- Read more about final keyword or modifier
1.1 Variable declared as final can’t be re-assigned
- Compile-time error: The final field FinalKeyword.count cannot be assigned
1.2 Method declared as final can’t be overridden
- Compile-time error: Cannot override the final method from ParentClass
1.3 Class declared as final can’t be extended/inherited
- Compile-time error: The type ChildClass cannot subclass the final class ParentClass
2. finally block:
- finally is a block associated with try-catch block in exception handling concept
- It is used to provide clean-up code for releasing resources used in try-block like database connection or IO resources or network resources
- The beauty of finally-block is that it is always gets executed, irrespective of whether exception is thrown or NOT and whether exception is handled or NOT
- Read more about finally block
FinallyBlockExample.java
package in.bench.resources.exception.handling;
public class FinallyBlockExample {
public static void main(String[] args) {
try {
// code which might raise exception
int result = 19/0;
System.out.println("Result of division : "
+ result);
}
catch(ArithmeticException aex) {
// corresponding handling code,
// if any exception from try block
System.out.println(aex.toString());
}
finally {
// finally block always gets executed
// for code clean-up activities
System.out.println("finally block"
+ " always gets executed");
// rest of the code clean-up
}
}
}
3. finalize() method:
- finalize() is a method is associated with garbage collector
- this method is invoked just before destroying an Object i.e.; to provide clean-up activities
- After Garbage Collector invokes finalize() method, then immediately it destroys an Object
- Programmer doesn’t have any control over the invocation of finalize() method because it is internally invoked by garbage collector for null objects (although, we can make Object as null by assigning to null reference)
Method signature:
protected void finalize() throws Throwable;
FinalizeMethodExample.java
package in.bench.resources.exception.handling;
public class FinalizeMethodExample {
protected void finalize() throws Throwable {
System.out.println("finalize() method invoked"
+ " to clean-up Object resources");
}
public static void main(String[] args) {
// create Object of type FinalizeMethodExample
FinalizeMethodExample fme = new FinalizeMethodExample();
// explicitly making null
fme = null;
}
}
Explanation:
- When above program is executed, it doesn’t print any sysout statement from finalize() method
- Because, it is the garbage collector’s duty to invoke finalize() method just before destroying the Object
- And hence programmer can’t make sure that it is compulsorily invoked although we can make any Object as null explicitly
Folks, it is your turn comment & suggest for improvement
Related Articles:
- Java – Exception Handling
- Java – Exception Hierarchy
- Java – 5 important keywords in Java Exception handling
- Java – Runtime mechanism, what happens when exception is thrown ?
- Java – Checked Exception v/s Unchecked Exception
- Java – Exception propagation
- Java – try-catch block
- Java – finally block
- Java – try with multiple catch blocks
- Java – Nested try-catch block
- Java – Returning value from method having try-catch-finally blocks
- Java – return statement with finally block
- Java – final v/s finally v/s finalize
- Java – Various methods to print exception information
- Java – throw keyword
- Java – throws keyword
- Java – throw v/s throws
- Java – Difference between throws clause and try-catch-finally block
- Java – Rules for Exception handling w.r.t Method Overriding
- Java – User-defined or Custom exception
- Java – Difference between ClassNotFoundException v/s NoClassDefFoundError
- Java – Top Exception and Error
- Java – Interview question and answers on Exception Handling
- Java 7 – try with resources
- Java 7 – multi-catch block
References:
- https://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html
- https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#finalize()
- https://docs.oracle.com/javase/tutorial/java/IandI/final.html
- https://docs.oracle.com/javase/tutorial/essential/exceptions/try.html
- https://docs.oracle.com/javase/tutorial/essential/exceptions/catch.html
- https://docs.oracle.com/javase/tutorial/essential/exceptions/
- https://docs.oracle.com/javase/7/docs/api/java/lang/Exception.html
- https://docs.oracle.com/javase/7/docs/api/java/lang/Error.html
- https://docs.oracle.com/javase/specs/jls/se7/html/jls-11.html
- https://docs.oracle.com/javase/7/docs/api/java/lang/ArithmeticException.html
- https://docs.oracle.com/javase/7/docs/api/java/lang/NullPointerException.html
- http://docs.oracle.com/javase/7/docs/api/java/lang/ArrayIndexOutOfBoundsException.html
- http://www.oracle.com/technetwork/java/effective-exceptions-092345.html
- http://otfried.org/courses/cs206/slides/slides-stackframes.pdf
Happy Coding !!
Happy Learning !!