Interview Question: Final vs Finally vs Finalize

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. Mostly the 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 like working on some projects. If you have any difficulties understanding please feel free to contact me on social media or comment down below. We will always be there to help you guys. I am mostly active on Linkedin. Social media we are on are, TwitterInstagramLinkedin, or Facebook.

final: The Constant

final keyword is used for various purposes. It is used on variables, functions or methods, and classes.

final variable

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 change 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
class Cirlce {
    private static final float PI = 3.14;
    private static final int SOME_OTHER_CONSTANT = 12345;
}

final class

Another use is by classes. Put final before class and no class can extend that class. This makes the class un-extendable (if that is a word). For example, the String class is a final class. You can not extend the String class.

public final class String {
// code
}
class AnotherClass extends String{ // compile time error

}

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 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
    }
}

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 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");
}

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 catched , 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 being garbage collected you want something to be done you can do 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
    }
}

final vs finally vs finalize

finalfinallyfinalize
keywordkeyword (block)method
used with class, variable, methodsused with try-catch blockoverridden method of Object
make the state constantruns the block of code even if no exception thrownruns just before objects get garbage collected
Syntax:
final varibaleName = someValue;
Syntax:
try{} catch() finally {}
Syntax:
public void finalize(){}
Example: String class, constant valuesExample: release the connection, filesExample: Some stuff before objects gets deleted
difference between final, finally, and finalize

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 the tricky questions and answers like this. Just don’t lose hope gain your knowledge not by reading only but 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 in 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.