Java

Difference between final, finally and finalize in Java

Posted on by

To be honest, only final and finally are reserved keywords in Java. The third one - finalize - is in fact a method and should be written like this: finalize(). Even though the first two sound similar, they have absolutely different purposes and use contexts.

Final

The final keyword is used to "flag" a variable, a method or a class as immutable. Hence, it can not be changed once it is defined/created. Our first three examples will cover variable, method and class definitions using the final keyword.

Example 1 (final variable):

public class MyCar {
    // Value of the variable can not be changed
    final Integer wheels = 4;

    public void addWheels(Integer amount) {
        // NOT ALLOWED, wheels are final, I want my car to have exactly 4 wheels!
        this.wheels += amount;
    }
}

Example 2 (final method):

public class MyCar {

    // I would like to ensure my car has wheels!
    public final Boolean hasWheels() {
        return true;
    }
}


public class MyCarModification extends MyCar {

    // NOT  ALLOWED, no modification on my car allowed in terms of wheels!
    public Boolean hasWheels() {
        return false;
    }

}

Example 3 (final class):

public final class MyCar {
    
    // Nice implementation of my car :)
    
}

// NOT ALLOWED, my car is perfect as it is!
public class MyCarModification extends MyCar {

    // Awful modifications to my car :(

}

Finally

Finally is always used in the context of a try/catch/finally block. It can not be used on variables, methods or classes. A try/catch block is usually used if the outcome of a computation is "unsafe". This means, the developer expects errors to happen. So, we try to execute some code (a: write to a database, b: open a file, c: connect to a server, ...) and catch exceptions (a: unique constraint violation, b: file not found, c: no internet connection, ...). In many cases try/catch is used to handle business logic flow, like showing a 404 page for not found content (I think a pretty bad idea). The finally part is optional and can be used to add code which will be executed after a try/catch. Hence, it doesn't matter if the computation fail or not.

Example 4 (finally keyword:

public class MyCar {

    public void driveLikeABoss() {
        
         try {
             // Do some fancy stuff here, which can throw two exceptions
             this.navigateToSydney():
         }
         catch (OutOfFuelException e) {
             // Maybe refuel?
         }
         catch (CrashedIntoOceanException e) {
             // Uhm, ok, build a new car and try again?
         }
         finally {
             // Drink some coffee
         }
    }

}

Finalize()

Finalize is a method which is defined in the Object class. The Java garbage collector will call this method right before Object destruction. In this case the JVM figured out that the object is not needed anymore (no references) and can be destroyed. Since this method was not defined as final (have a look at Example 2) we can override it and adapt to our needs.

Example 5 (finalize() method):

class MyCar {

    protected void finalize() throws Throwable {

        System.out.println("All your car are belong to us");

    }

}

Please note that we expect this method to throw any kind of Exceptions (even though I don't recommend to do so). This functionality is useful for cleaning up, maybe releasing resources, closing fles, ...

I hope this little blog post helps you to understand the difference between final, finally and finalize. If you have any additional thoughts or comments, please feel free to drop some lines in the section below.