Final, Finally and Finalize Methods in Java

Final Keyword in Java

 
Final is a keyword or reserved word in Java.
 
The final keyword in Java can be used in the following three ways:
  • Class
  • Method
  • Variables

Final Variable in Java

 
If a variable is declared as final then it cannot be reinitialized after it. Final variables are often declared with the static keyword in Java and treated as constant. Here is an example of a final variable in Java. Final variables are by default read-only.
 
Final member variables need to be initialized at the time of declaration or we can also initialize it inside the constructor. If we fail to do so it will result in a compilation error.
 
The final keyword can be applied with variables that have no value and then it is called a blank final variable. A blank final variable forces the constructors to initialize it. It can be static also and will be initialized in the static block of code only.
  • It is used to indicate that a local variable cannot be changed once its value is set;
  • It is used to indicate that a static variable cannot be changed once set, in effect implementing "constants";
  • It is used to indicate that a value of an instance variable cannot be changed once set; this makes accesses to that variable thread safe.
For Example
 
final double PI = 3.14;
PI = 1234; // does not compile
 
Example
  1. public class FinalVariable  
  2. {  
  3.     final int a = 10;  
  4.     public void showValue()  
  5.     {  
  6.         System.out.println("Final variable value : " + a);  
  7.     }  
  8.     public static void main(String[] args)  
  9.     {  
  10.         FinalVariable ob1 = new FinalVariable();  
  11.         ob1.showValue();  
  12.     }  
  13. }  
Output
 
variable.jpg
 

Final Class in Java

 
A Java class with the final modifier is called a final class in Java. Java classes that are declared as final cannot be extended, in other words, inheritance is restricted. In other words, a final class cannot be subclassed further. This is done for security and efficiency purposes.
 
It is used to indicate that a class cannot be extended. If a class is final then all of its methods are implicitly final as well, that is, the method is guaranteed not to be overridden in any subclass. 
 
Syntax
 
public final class MyFinalClass
{
???..
}
 
Basic Example
  1. final class FinalClass  
  2. {  
  3.     public final int a;  
  4.     public final int b;  
  5.     MyFinalClass(int x, int y)  
  6.     {  
  7.         a = x;  
  8.         b = y;  
  9.     }  
  10. }  
Example
  1. class value  
  2. {  
  3.     int x, y;  
  4. }  
  5. class point extends value  
  6. {  
  7.     int a;  
  8. }  
  9. final class val extends point  
  10. {  
  11.     int z;  
  12. }  
  13. class FinalClass  
  14. {  
  15.     public static void main(String args[])  
  16.     {  
  17.         val Obj = new val();  
  18.         Obj.z = 10;  
  19.         Obj.a = 1;  
  20.         Obj.x = 5;  
  21.         Obj.y = 8;  
  22.         System.out.println("x = " + Obj.x);  
  23.         System.out.println("y = " + Obj.y);  
  24.         System.out.println("z = " + Obj.z);  
  25.         System.out.println("a = " + Obj.a);  
  26.     }  
  27. }  
Output
 
class.jpg 
 

Final Method in Java

 
The final keyword in Java can also be applied to methods. A Java method with the final keyword is called a final method and it cannot be overridden in a sub-class. You should make a method final in Java if you think it's complete and its behavior should remain constant in sub-classes.
 
In methods private is equal to final, but in variables, it is not.
 
Note: If we make a class both "private" and "final" then the "final" keyword is dismissed as a private method that cannot be accessed in its subclass. But you'll successfully be able to declare a method of the same name as in the base class if the method has been made private in the base class, then it doesn't mean you're overriding the method. You're simply declaring a new method in the subclass.
 
Note: You cannot make an "abstract" class or method as "final" because an "abstract" class needs to be extended that will not be possible if you make it "final".
 
Syntax
  1. public class FinalMethod  
  2. {  
  3.   public final void myFinalMethod()  
  4.    {   
  5.    ???...  
  6.    ????  
  7.    }  
  8. }  
Example
  1. class Method  
  2. {  
  3.     int a = 2;  
  4.     int b = 3;  
  5.     final void showValue() {  
  6.         System.out.println("First number value :" + a);  
  7.         System.out.println("Second number value :" + b);  
  8.     }  
  9. }  
  10. class Method1 extends Method  
  11. {  
  12.     /*It can not overridden. Because it is declared as final in super class. 
  13.      void showValue() 
  14.       { 
  15.       System.out.println("Final method can not overridden."); 
  16.       } 
  17.      */  
  18. }  
  19. public class FinalMethod  
  20. {  
  21.     public static void main(String[] arg0)  
  22.     {  
  23.         Method ob = new Method();  
  24.         ob.showValue();  
  25.     }  
  26. }  
Output
 
method1.jpg
 

Advantages of Final Keyword in Java

  • Final keyword improves performance. Not just JVM can cache the final variable but also the application can cache frequently used final variables.
  • Final variables are safe to share in multithreading environments without additional synchronization overhead.
  • Final keyword allows JVM to optimize a method, variable or class.
Note: Final is different than the finally keyword that is used on an Exceptional Handling in Java and also final should not be confused with the "finalize()" method that is declared in the object class and called before an object is a garbage collected by JVM.
 

Finally Keyword in Java

 
The finally block, if used, is placed after a try block and the catch blocks that follow it. The finally block contains code that will be run whether or not an exception is thrown in a try block.
 
In Java, there are three clauses named try, catch and finally used as exception handler components. You use it in combination with "try" and "catch". Any commands after "finally" will be run whether there is an error or not. Cleanup commands are typically placed here.
  • The finally block always executes immediately after try-catch block exits.
  • The finally block is executed in case even if an unexpected exception occurs.
  • The runtime system always executes the code within the finally block regardless of what happens in the try block. So it is the ideal place to keep cleanup code.
Note: If the JVM exits while the try or catch code is being executed, then the finally block may not execute. Likewise, if the thread executing the try or catch code is interrupted or killed, then the finally block may not execute even though the application as a whole continues.
 

Importance of Finally Block

 
The finally block is a key tool for preventing resource leaks. When closing a file or otherwise recovering resources, place the code in a finally block to ensure that resources are always recovered.
 
Syntax
  1. public void someMethod{  
  2.    Try   
  3.    {  
  4.    // some code  
  5.    }  
  6.    Catch(Exception x)   
  7.    {  
  8.    // some code  
  9.    }  
  10.    Catch(ExceptionClass y)   
  11.    {  
  12.    // some code  
  13.    }  
  14.    Finally  
  15.    {  
  16.    //this code will be executed whether or not an exception  
  17.    //is thrown or caught  
  18.    }  
  19. }  
Example
  1. public class FinallyBlock  
  2. {  
  3.     public static void main(String[] a)  
  4.     {  
  5.         /** 
  6.          * Exception will occur here, after catch block 
  7.          * the contol will goto finally block. 
  8.          */  
  9.         try  
  10.         {  
  11.             int i = 10 / 0;  
  12.         } catch (Exception ex)  
  13.         {  
  14.             System.out.println("Inside 1st catch Block");  
  15.         } finally  
  16.         {  
  17.             System.out.println("Inside 2st finally block");  
  18.         }  
  19.         try  
  20.         {  
  21.             int i = 10 / 10;  
  22.         } catch (Exception ex)  
  23.         {  
  24.             System.out.println("Inside 2nd catch Block");  
  25.         } finally  
  26.         {  
  27.             System.out.println("Inside 2nd finally Block");  
  28.         }  
  29.     }  
  30. }  
Output
 
finally.jpg
 

Finalize Method in Java

 
The Finalize() method is defined in the "java.lang.Object" class, which means it is available to all the classes for the purpose of overriding and its modifier is defined as protected. The finalize() method is not public because it should only be invoked by JVM and not by anyone else and protected so that it can be overridden by the subclasses.
 
Java uses a finalize method for garbage collection. Before an object is garbage collected, the runtime system calls its finalize() method. The intent is for finalize() to release system resources such as open files or open sockets before being collected.
 
The finalize() method is called before the Garbage collector reclaims the Object, it's the last chance for any object to perform the cleanup activity i.e. releasing any system resources held, closing the connection if open etc. The Finalize method in Java is a special method much like the main method in Java.
 
When not to use the finalize() method
 
1. The finalize method is not automatically chained like constructors. That means:
  • when you call a constructor then constructors of all super classes will be invoked implicitly. But, in case of finalize methods, this is not followed. The Super class's finalize() should be called explicitly.
  • If you are overriding the finalize method then it's your responsibility to call the finalize() method of the super-class, if you forgot to call it then the finalize of the super class will never be called. So it becomes critical to remember this and provide an opportunity to call finalize of the super class to perform cleanup. The best way to call the super class finalize method is to call them in a finally block.
2. The finalize method is called by the garbage collection thread before collecting the object and is not intended to be called like a normal method.
 
3. Finalize is to be called only once by the GC thread, if the object revives itself from the finalize method then finalize will not be called again.
 
4. Any Exception thrown by a finalize method is ignored by the GC thread and it will not be propagated further.
 
How to correctly use the Finalize() method
  • Always call "super.finalize()" in your finalize() method.
  • Do not use "Runtime.runFinalizersOnExit(true);" as it can put your system in danger.
  • We can run the finalize method by calling "System.runFinalization()" and "Runtime.getRuntime().runFinalization()". These methods ensure that the JVM calls the finalize() method of all objects eligible for garbage collection and whose finalize has not yet been called.
Finalize() Method declaration
  1. protected void finalize() throws Throwable  
Example of how use the Finalize() method in Java
  1. @Override  
  2. protected void finalize() throws Throwable  
  3. {  
  4.     try  
  5.     {  
  6.         System.out.println("Finalize of Sub Class");  
  7.         //release resources, perform cleanup ;  
  8.     } catch (Throwable t)  
  9.     {  
  10.         throw t;  
  11.     } finally  
  12.     {  
  13.         System.out.println("Calling finalize of Super Class");  
  14.         super.finalize();  
  15.     }  
  16. }  

Difference between Final, Finally and Finalize in Java

 
Final
  • When a class is marked final, it cannot be subclassed.
  • When a method is marked final, it cannot be overridden by the subclass.
  • And when a field is marked final, its value, once set, cannot be reset or changed. 
Finally
 
Finally is used in try-catch (i.e. exception handling in Java). Each try contains one and only one finally block. It is a block associated with the try-catch; the main objective of a finally block is to maintain cleanup code that should execute always.
 
Finalize
 
It is a method should be executed by the "Garbage Collector" just before destroying an object. The main objective of a finalize method is to maintain cleanup code. Finalize is a method. Before an object is garbage collected, the runtime system calls its finalize() method. You can write a system resources release code in a finalize() method before getting garbage collected.
 
Note: when compared with finalize, finally is always recommended to maintain cleanup code because there is no guarantee for the exact behaviour of the "Garbage Collector"; it is Virtual Machine Dependent.


Similar Articles