Full Question:
In Java, what is the difference between final, finally, and finalize?
- final – Define an entity once that cannot be changed nor derived from later. More specifically: a final class cannot be subclassed, a final method cannot be overridden, and a final variable can occur at most once as a left-hand expression. All methods in a final class are implicitly final.
Example.
// final class
public final class MyFinalClass {...}
// final method
public class MyClass {
public final void myFinalMethod() {...}
}
//final variable
public class Sphere {
public static final PI = 3.141592653589793; // a constant
public final double radius;
Sphere(double r) {
radius = r;
}
}
- finally – The finally block always executes when the try block exits, except System.exit(0) call. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.
Example.
try {
System.out.println("Entering second try block");
try {
throw new MyException();
} finally {
System.out.println("finally in 2nd try block");
}
} catch (MyException e) {
System.err.println("Caught MyException in 1st try block");
} finally {
System.err.println("finally in 1st try block");
}
Result:
Entering second try block
finally in 2nd try block
Caught MyException in 1st try block
finally in 1st try block - finalize() – method helps in garbage collection. A method that is invoked before an object is discarded by the garbage collector, allowing it to clean up its state. Should not be used to release non-memory resources like file handles, sockets, database connections etc because Java has only a finite number of these resources and you do not know when the garbage collection is going to kick in to release these non-memory resources through the finalize() method.
Example.
protected void finalize() throws Throwable {
try {
close();
} catch(Exception e) {
} finally {
super.finalize();
}
}
In Java, what is the difference between final, finally, and finalize?