Hey, Tea Lovers! Today let’s look at the most asked, tricky, and fumbled interview question i.e. What is the difference between final, finally, and finalize in Java? Most beginners face this question. The thing is, only their names are the same the work is completely unrelated.
I know you are in a hurry to prepare for the interview, so I will make this post as short as possible. But before reading, prepare your cup of tea to sip and code.
For beginners, a word of advice is, don’t worry too much and enjoy your learning. There are things you will understand along the way, being humble about the knowledge is the key. There is always something to learn. But only reading won’t get you anywhere. You have to do something such as work on some projects. If you have any difficulties understanding please feel free to contact me on social media or comment.
I would be happy to connect with you guys on social media. It’s @coderstea on Twitter, Linkedin, Facebook, Instagram, and YouTube.
Please Subscribe to the newsletter to know about the latest posts from CodersTea.
final Keyword in Java: The Constant
final
keyword is used for various purposes. It is used on variables, functions or methods, and classes.
the final variable in Java
One common use is to make variables constant i.e the value assigned to them can’t be changed by reassigning. For example, the PI value. The value does not change thus a constant value. So we can define the PI variable as a final and the value won’t be changed throughout its use.
final float PI = 3.14;
float radious = 4;
double circleArea = PI * radious * radious;
PI = 12345.23; // compile time error: can't reassign the value to final variable
Code language: PHP (php)
class Cirlce {
private static final float PI = 3.14;
private static final int SOME_OTHER_CONSTANT = 12345;
}
Code language: PHP (php)
the final class in Java
Another use is by classes. Put final
before class and no class can extend that class. This makes the class unexpendable (if that is a word). For example, the String class is final. You can not extend the String class.
public final class String {
// code
}
class AnotherClass extends String{ // compile time error
}
Code language: PHP (php)
This comes in handy when you don’t want any other class to alter or mimic the class or immutable class, String. But many people argue that it violates the concept behind the OOP. But in the end, it all depends on the requirements, isn’t it?
final method or function in Java
In case you don’t want to allow the subclass to override the function mark it as final. This will prevent it to be overridden by the subclass. For example, if you have some business logic and want to enforce the same logic in all the subclasses. You can not override the final method, but of course, you can still call the method via the subclass.
class SomeClass {
public String canBeOverride() {
return "SomeClass function"
}
public final int cantOverrideThis() {
// some business logic
return 1;
}
}
class SomeOtherClass extends SomeClass {
@Override
public String canBeOverride() {
return "Some Other class function";
}
// compile time error
// can't override final method
@Override
public int cantOverrideThis() {
// some business logic
return 1;
}
}
public class Main {
public static void main (String args[]){
// you can't override, but you can call the final method
// make sure to delete the overridden block from SomeOtherClass
// to avoid compile time error
new SomeOtherClass().cantOverrideThis(); // will return 1
}
}
Code language: PHP (php)
The one thing common against class, variable, and method is that final is not allowing it to be changed. The final class can’t be subclasses so no modification in it via inheritance. Once defined, the variable’s value can’t be changed. The method isn’t allowed to change its behavior by overriding. So the final is to make things constant.
finally: The try-catch Companion
Sounds similar but no they are not twins. The finally
keyword is used with the try-catch block. Run a block of code without considering if the exception is thrown or not. It will run after the try or catch block or we return something in between.
try{
// some code
} catch (Exception e){
e.printStackTrace();
} finally {
System.out.println("I will run no matter what.");
}
try{
// some code
if(something) return 0;
//some other code
} catch (Exception e){
e.printStackTrace();
} finally {
System.out.println("I will run even though try is returning before ending.");
}
try{
throw new Exception("some error");
} catch (Exception e){
e.printStackTrace();
} finally {
System.out.println("I will run after exception has been catched");
}
Code language: PHP (php)
In the first block, if everything goes right and try bock ends successfully finally block will be called. In the second block even if we are returning finally block will be called. The third block throws an exception and is caught, but notice, finally block is still getting called. So no matter what exception or not, returned or not, finally block will be called.
Used mostly in JDBC when we want to close the connection no matter the exception. Or while reading and writing the file, we have to close the stream or release the file.
finalize: The Last Wish Before Death
Unlike the other two, finalize
is a function rather than a keyword. It is an overridden function of the Object class. When the garbage collector is ready to remove the object and can not see any other visible reference to the object, JVM calls this finalize method of the object. Before garbage is collected you want something to be done you can do it in the finalize method. However, since Java 9 the method has been deprecated.
class SomeClass{
@Override
protected void finalize() throws Throwable {
System.out.println("This object is being garbage collected.");
// dome some stuff like release some resources
}
}
Code language: JavaScript (javascript)
final vs finally vs finalize
final | finally | finalize |
keyword | keyword (block) | method |
used with class, variable, methods | used with a try-catch block | overridden method of Object |
make the state constant | runs the block of code even if no exception is thrown | runs just before objects get garbage collected |
Syntax: final varibaleName = someValue; | Syntax: try{} catch() finally {} | Syntax: public void finalize(){} |
Example: String class, constant values | Example: release the connection, files | Example: Some stuff before objects get deleted |
Conclusion
We talked about the difference between final, finally, and finalize. Explored in detail about them and a short comparison side by side. For beginners, it might be a lot to digest but trust me, it will get cleared once you start working. Most of the time interview is about tricky questions and answers like this. Just don’t lose hope to gain your knowledge not by reading only but by working on some stuff side by side.
I have posted some posts that will help you, such as “Mistakes Probably Every Programmer and I Made at the Beginning” and “Most Loved Interview Question: How HashMap works in Java“.
Hope you liked the post. If you want to discuss something and clear out some questions related or unrelated to this topic, please free to comment. or Follow us on social media. See you in the next post.
See you in the next post. HAKUNA MATATA!!!
I would be happy to connect with you guys on social media. It’s @coderstea on Twitter, Linkedin, Facebook, Instagram, and YouTube.
Please Subscribe to the newsletter to know about the latest posts from CodersTea.