What is the difference between final, finally and finalize in Java?
They look alike and they have almost nothing to do with each other. Here is what each one does.
The word final is a restriction. It says that something cannot change after it has been set. A final variable cannot be given a new value. A final method cannot be overridden. A final class cannot be extended.
The word finally is a block of code. It runs after a try block, whichever way that block was left, whether it finished normally, threw an error, or returned early.
The word finalize was a method that every class inherited from Object. The garbage collector was supposed to call it just before it freed an object, which gave the object a last chance to tidy up after itself.
So the summary is this. The word final stops a change. The word finally is a block that always runs. The word finalize was a method for cleaning up, and it should not be used any more.
public class Main {
public static void main(String[] args) {
// final stops a change.
final int limit = 10;
System.out.println("limit : " + limit);
// finally always runs.
try {
System.out.println("in the try");
} finally {
System.out.println("in the finally");
}
}
}
The next question in this topic explains why you should not use the third one.