What is difference between final vs finally and finalize in Java?

Hello guys, final, finally, and finalize are three confusing keywords, modifiers, and methods in Java. They sound similar, but they are for different purposes. For example, the final keyword is a modifier in Java. When you use the final keyword with a class, it becomes a final class, and no one can extend this like String is final in Java. When you use the final modifier with a method, then it cannot be overridden in a subclass, and when you use the final keyword with a variable, it becomes a constant, i.e. its value cannot be changed once assigned.

On the other hand, finally is a keyword related to exception handling in Java. It's often used with a try block, and it's part of try, catch, and finally trio.

Also, the finally block can be used with or without a catch block in Java, and it's guaranteed to be always executed, irrespective of what happens inside the try neighborhood. This is the reason why the final block is used to do cleanup and free resources.

The third one i.e. finalize(), is a method in java.lang.Object class and part of Java's garbage collection process. A garbage collector is supposed to call the finalize() method before reclaiming memory from a dead object in Java.

Remember, it's supposed to be called, but it's not guaranteed; hence, it's not reliable, and thus, there is no practical use of finalize() method in Java. This was the fundamental difference between final, finalize(), and finally in Java.

If you are interested to learn more about these concepts, you can further check The Complete Java Masterclass course on Udemy to learn more about them, particularly how to use finally block because that's the key piece of error handling in Java.  Anyway, let's see some more points to understand their differences better in Java.





Difference between final vs. finally vs. finalize in Java

The difference is given in the first paragraph about the final, finally and finalize() method is sufficient from an interview point of view but it's better to know some more differences if you want to impress the interviewer or want to prepare better for follow-up questions. Let's see a couple of more points to learn this concept better.


1) First and foremost, even though their name sounds similar, final, finally, and finalize() are completely different from each other. There is no similarity in their function; whatever is, it's only on their names.


2) The final keyword can be used with a class, method, or variable in Java. A final class is not extensible in Java, a final method cannot be overridden, and a final variable cannot be changed. You can make a class Immutable in Java by using the final keyword. Similarly, you can prevent overriding by using the final keyword with a method and you can declare a static final method to represent constant values.


3) You need either a catch or a finally block with a try block in Java. The main advantage of the finally block is that it's guaranteed to be executed even if your try block throws an exception.

There is only one scenario when finally block doesn't get executed, when JVM crashes, or you call System.exit() or Runtime.exit() from the try block.

See Java Fundamentals: The Java Language on Pluralsight to learn more when finally block doesn't execute and what happens during JVM crash, e.g. whether shutdown hook runs or not.

Difference between final vs finally and finalize in Java? Answer




3.1) A finally block can also override return values; for example, if a try block return 10 and finally block return 20, then the method will return 20. Any value returned from the finally block will be used.

Even though the finally block is guaranteed to be executed, many developers make the mistake of closing streams in finally block without realizing that the close() method itself can throw an exception and can leave other streams open.

That's why the right way to close the stream in Java is to use a separate try-catch or try-finally block inside finally block in Java, it's also an exception handling best practice in Java, as shown below:

Stream stream = null;
try{
  stream = open();
  // do something with stream
}finally{
  if(stream != null){
    try{ stream.close()}catch{}
  }
}



4) Last, the finalize() method is one of the seven methods declared inside java.lang.Object class. As per Java specification, it's supposed to be called on the object before it gets garbage collected.

It is supposed to give the last chance to the object to do cleanup or resurrect itself, but the main problem is that it's not guaranteed to be called.

Due to this reason, finally block is not useful in Java. Even the great Joshua Bloch has advised against using the finalize method in the classic Effective Java book, but this quote from Google coding standard effectively summarizes the finalize() method in Java.


Difference between final, finally and finalize method in Java


That's all about the difference between final, finally, and finalize in Java. As I said, all three are completely different from each other, the only similarities are that their name sounds similar. The final is a modifier that can be used with class, method, or variable in Java. The finally block is used along with the try block in Java and finalize() is a method which is called by Garbage collector just before the object is garbage collected.


Some other interesting core Java interview questions you may like
  • How ConcurrentHashMap works in Java? (answer)
  • Why Java doesn't support operator overloading? (answer)
  • 130+ Java Interview Questions from the last 5 years (questions)
  • Why wait and notify should always be called in a synchronized context? (answer)
  • 21 String algorithms questions for coding interviews (questions)
  • Why a character array is better than a String for storing passwords? (answer)
  • Why double-checked locking idiom was broken before Java 5? (answer)
  • 100+ Coding interview Questions for Programmers (questions)
  • Why you shouldn't use == to compare float and double in Java? (answer)
  • Why do we use SerialVersionUID in the Java class? (answer)
  • Difference between Thread and Runnable in Java? (answer)
  • How to avoid deadlock in Java while Coding? (solution)
  • Difference between Runnable and Callable in Java (answer)
  • 50+ Java Thread Interview Questions for Programmers (questions)
Thanks for reading this article so far. If you like this article, then please share it with your friends and colleagues. If you have any questions or feedback, then please drop a note.

P. S. - If you are preparing for a Java Interview then you can also check this list of courses to prepare well for your Java Interviews and if you want to learn Java in depth. 

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.