Skip to main content

Difference between Final, Finally and Finalize in Java


In your java journey sometimes you confuse about these three final words. but now we remove this confusion in this article. so lets go differentiate these three terms.

What is final, finally and finalize in simple terms?

Final :-
Final is keyword in java. final means it can not be changeable.
We can use final keyword in following three cases:-
  1. Final Class
  2. Final Variable
  3. Final Method
If we declare class as final then we can not extends that class. if we try to extends final class then we get error.
If we declare variable as final means we can not reassign its value means we can not change if we declare variable final.
And last id we declare method as final then we can not override that methods. means can not overridden final method.
I created full article about Final keyword in java you can check here.

Finally :-
Finally is block in java. It is simple block.
Finally {
    // Finally block
    System.out.print("In finally block");
}
Finalize :-
Finalize is method in java. Finalize method is available in Object class.
Finalize method is called before object is destroyed in java.

So we discuss in simple term what is final, finally and finalize so now lets see in brief using example so you can understand better.

Final Keyword:-

You can refer this for final keyword in java. in this i explain briefly what is final keyword, class, variable, method.

Finally Block :-

Finally block is used with try catch block. try catch block are used for exception handling in java.
Finally block executed always if exception caught or not. so finally block is used when you want to do something if exception occurred or not.

Can we use finally block without catch block in java?
Yes, in java we can also use finally block without catch block.

Finally block is used to execute important code like free memory usages, cleanup resource, etc. So used this kind of code in finally block is good practice.

So lets see example.
Example 1 :- Finally block when exception not caught means exception not occurred.
public class FinallyDemo {

    public static void main(String[] args) {

        int number1 = 10;
        int number2 = 10;
        int answer;
        try {
            System.out.println("In try block");
            answer = number1 / number2;
        } catch(Exception e) {
            System.out.println("Exception occurred");
        } finally {
            System.out.println("Finally");
            System.out.println("It is always executed if error caught or not");
        }
      
    }
}

Output :-
In try block
Finally Block.
It is always executed if error caught or not.

In above example exception is not occurred but Finally block executed. 
Now lets see how finally block work when exception is caught.
Example 2 :- Finally block when exception caught by catch block
public class FinallyDemo {

    public static void main(String[] args) {

        int number1 = 10;
        int number2 = 0;
        int answer;
        try {
            System.out.println("In try block");
            answer = number1 / number2;
        } catch(Exception e) {
            System.out.println("Exception occurred: " + e);
        } finally {
            System.out.println("Finally Block.");
            System.out.println("It is always executed if error caught or not.");
        }
      
    }
}
Output :-
In try block
Exception occurred: java.lang.ArithmeticException: / by zero
Finally Block.
It is always executed if error caught or not.

In above example DivideByZero exception is caught by catch block but finally block also executed.

Finalize Method :-

  • Finalize method defined in java.lang.Object class which is parent of all java classes.
  • Finalize method is execute before object is destroyed like we discuss above.
  • In simple term, finalize method called before garbage collection on particular object.
  • Finalize method called by garbage collector when object are not referenced anywhere in code and have been selected for garbage collection. means object that are not used anymore.
  • Finalize method calls only once by Garbage Collector thread. If object revives from finalize method then finalize method does not call again.

Finalize get invoked when JVM (Java Virtual Machine) find out that particular object should be garbage collected.

Syntax of finalize method:-
protected void finalize throws Throwable { }

For call garbage collection manually we have to call gc() method. so lets see example of that.

public class FinalizeDemo {

      public static void main(String[] args)  
        {  
             FinalizeDemo obj = new FinalizeDemo ();  
             System.out.println(obj.hashCode());  
        
             // Set object to null so it is garbage collected.
             obj = null;  

             // calling garbage collector   
             System.gc();  
             System.out.println("end of garbage collection");  
             System.out.println(obj.hashCode());  

        }      
}

Output :-
617901222
end of garbage collection
Exception in thread "main" java.lang.NullPointerException
    at FinalizeDemo.FinalizeDemo.main(FinalizeDemo .java:13)


We created object of FinalizeDemo class and print hash code of that object. after we set null to object so we can call garbage collector for clear that object after set null we call gc method for garbage collected.

Finally after cleared that object if we again call hashCode method we get error because that object is clear from memory.

When Finalize method called in Java?
In simple term, The finalize method will be called after the Garbage Collector detects that the object is no longer reachable, and before it actually reclaims the memory used by the object.
Check out this for more info.

Why we override finalize method in java?
In general it is best practice to not rely on finalize() method to do any clean up activity.
In general it's best not to rely on finalize() to do any cleaning up etc.
  • You should override finalize when your class has resources that won't be cleaned up by the Garbage Collector, such as file handles or database connections.
  • When you set available object references to null after the purpose of creating the object is done.
  • When you make the reference variable to refer to another object.
Check out StackOverflow answers for more info :-

Check java doc for more.

if you want to learn more about Finalize method check this article :-

Comments

Popular posts from this blog

Plus Minus HackerRank Solution in Java | Programming Blog

Java Solution for HackerRank Plus Minus Problem Given an array of integers, calculate the ratios of its elements that are positive , negative , and zero . Print the decimal value of each fraction on a new line with 6 places after the decimal. Example 1 : array = [1, 1, 0, -1, -1] There are N = 5 elements, two positive, two negative and one zero. Their ratios are 2/5 = 0.400000, 2/5 = 0.400000 and 1/5 = 0.200000. Results are printed as:  0.400000 0.400000 0.200000 proportion of positive values proportion of negative values proportion of zeros Example 2 : array = [-4, 3, -9, 0, 4, 1]  There are 3 positive numbers, 2 negative numbers, and 1 zero in array. Following is answer : 3/6 = 0.500000 2/6 = 0.333333 1/6 = 0.166667 Lets see solution Solution 1 import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.function.*; import java.util.regex.*; import java.util.stream.*; import static jav...

Flipping the Matrix HackerRank Solution in Java with Explanation

Java Solution for Flipping the Matrix | Find Highest Sum of Upper-Left Quadrant of Matrix Problem Description : Sean invented a game involving a 2n * 2n matrix where each cell of the matrix contains an integer. He can reverse any of its rows or columns any number of times. The goal of the game is to maximize the sum of the elements in the n *n submatrix located in the upper-left quadrant of the matrix. Given the initial configurations for q matrices, help Sean reverse the rows and columns of each matrix in the best possible way so that the sum of the elements in the matrix's upper-left quadrant is maximal.  Input : matrix = [[1, 2], [3, 4]] Output : 4 Input : matrix = [[112, 42, 83, 119], [56, 125, 56, 49], [15, 78, 101, 43], [62, 98, 114, 108]] Output : 119 + 114 + 56 + 125 = 414 Full Problem Description : Flipping the Matrix Problem Description   Here we can find solution using following pattern, So simply we have to find Max of same number of box like (1,1,1,1). And ...