Java final, finally and finalize

Final, Finally, finalise is a separate concept in Java, each with a unique function within the language.

Final is a keyword in Java. When applied, it turns a variable into a constant, meaning its value is unchangeable. When applied to a method, it signifies that subclasses are not allowed to override the method. When a class encounters this, it indicates that subclassing is not possible.

Finally: Whether or not an exception is raised, the code enclosed in the finally block will always be executed.

Finalize: The Object class defines the finalize method. The garbage collector calls it before recovering the memory that an object previously occupied.

Difference between Java final, finally and finalize

Final

  • The final keyword is employed in various situations.
  • When applied, it turns a variable into a constant, meaning that its value is unchangeable.
  • When applied to a method, it signifies that subclasses are not allowed to override the method.
  • When a class encounters this, it indicates that subclassing is not possible.

Finally

When handling exceptions, the finally block is used to ensure that a specific block of code is executed, regardless of whether an exception is thrown. Cleaning up resources, such as files or network connections, is one of its frequent uses.

Finalize

One method defined in the Object class is the finalize method. The garbage collector calls it before recovering the memory that an object previously occupied. However, because finalize is unpredictable, using it for resource cleanup is discouraged. Other resource management strategies, such as try-with-resources, are also advised.

Definition of Final

The final element is the keyword and access modifier used to apply restrictions to a class, method, or variable.

Java final Example

public class FirstCode{  
      final int age = 18;  
    void display() {  
    age = 55;  
    }  
    public static void main(String[] args) {  
    FirstCode obj = newFirstCode();   
    obj.display();  
    }
}

Java finally Example

In the following example, we’ll see how Java throws an exception that a catch block handles. The finally block will run after the try-catch block. If not, the remaining code will be executed normally.

public class FirstCode{    
      public static void main(String args[]){   
      try {    
        System.out.println("Inside try block");   
       int data=25/0;    
       System.out.println(data);    
      } 
      catch (ArithmeticException e){  
        System.out.println("Exception handled");  
        System.out.println(e);  
      }   
      finally {  
        System.out.println("finally block is always executed");  
      }    
      System.out.println("rest of the code...");    
      }    
    }

Java finalize Example

public class FirstCode{    
     public static void main(String[] args)     
    {     
        FirstCode obj = new FirstCode();       
        System.out.println("Hashcode is: " + obj.hashCode());           
        obj = null;    
        System.gc();     
        System.out.println("End of the garbage collection");     
    }      
    protected void finalize()     
    {     
        System.out.println("Called the finalize() method");     
    }     
}
S.No key Final Finally Finalize
1. Definition A key and access modifier, which is declared as a final keyword, is used to set limit values for classes, methods, or variables. Finally, the block that handles Java exceptions, Special code is run if there is no exception. In Java, the finalize keyword is used to tidy up an object right before it is collected.
2. Applicable to Use the Final keyword to specify classes, methods and variables. Finally, the block relates to a try and retrieve block as far as exception handling is concerned.  The finalize() method is used for handling objects.
3. Functionality Once declared, the final variable is immutable and cannot be changed. The finally block is used to ensure that a specific block of code is executed, regardless of whether an exception is thrown. Before destroying the object, the completion method performs a cleansing operation on it.
4. Execution We only execute the last method when it is called. The last block will be executed once the trycatch block is completed.  The finalize method is executed just before the object is destroyed.

How does the finalize() Method Work with Garbage Collection?

  • The JVM calls the garbage collector to remove unreferenced items as explained above.
  • It calls the finalize() method to perform a clean operation, and the garbage collector destroys the object after determining objects that have no references.

Let’s see some code to understand this:

public class Demo
{
    public static void main(String[] args)
    {
        String a = "Hello World!";
        a = null; 
    }
}

Suppose the value of a String object in this program is Hello World!. The string object is being discussed. There is no connection if that value is invalid. Therefore, it is entitled to collect waste. Before you destroy your object, the garbage collector will call finalize() to clean it up.

Final keyword

final (lowercase) is a reserved keyword in Java. Because it’s reserved, we can’t employ it as an identifier. This keyword may also be used with variables, methods and classes. Depending on the type of variable, class, or method to be used, the last keyword in Java has another meaning.

Final with variables

You cannot change the value of a variable after it has been initialized.

class FirstCode {
    public static void main(String[] args)
    {
        int a = 5;
        final int b = 6;
        a++;
        b++;
    }
}

Final with the class

The class cannot be subclassed. Every time we declare a class to be final, it means that we can’t extend that class, or that class can’t be extended, or that class can’t be made a subclass of that class.

final class FirstCode {
    public static void main(String[] args)
    {
        int a = 10;
    }
}
class First extends FirstCode{
    // more code here with main method
}

final with Method

The subclass is not allowed to override the method. As soon as a process is declared final, it cannot be overridden.

class FirstCode {
    final void rr() {}
    public static void main(String[] args)
    {
    }
}

class First extends FirstCode {
    void rr() {}
}

Conclusion

In conclusion, understanding the distinctions between final, finally, and finalize is essential for writing robust and maintainable Java code.

  • Use final to create constants, make methods or classes unmodifiable, or prevent subclassing.
  • Use finally for cleanup operations in exception handling, ensuring that particular code is executed regardless of whether an exception occurs or not.
  • Avoid using finalize for resource cleanup due to its unpredictability and use more modern approaches like try-with-resources for effective resource management.

By grasping the nuances of these concepts, Java developers can enhance code readability, maintainability, and avoid potential pitfalls associated with resource management and exception handling.

Leave a Reply

Your email address will not be published. Required fields are marked *