The following article describes Java Keywords – final, finally, and finalize.

What is the difference between final, finally and finalize in Java?

  • Actually, final is a keyword that is used to declare a constant or prevent a class, method, or variable from being overridden or subclassed.
  • Likewise, finally is a block of code that is used in conjunction with a trycatch statement to ensure that a certain piece of code is executed, regardless of whether an exception is thrown.
  • Thirdly, finalize is a method that is called by the garbage collector before an object is garbage collected. This method can be overridden to perform cleanup tasks before the object is destroyed.

Examples of Java Keywords – final, finally, and finalize

Using the final Keyword in Java

The following example demonstrates the use of final keyword in Java with a variable.

final int MAX_VALUE = 100;

Likewise, we can use final with a method.

class MathUtil {
  final void printMaxValue() {
    System.out.println(MAX_VALUE);
  }
}

Also, we can use final with a class.

final class Circle {
  final double PI = 3.14;
  ...
}

Using finally

Similarly, the following example code demonstrates the use of finally keyword. Basically, we use the “finally” keyword in Java in a try-catch block to specify a block of code that will execute always. No matter whether or not there is an exception. Accordingly, we use the “finally” block to clean up resources or close open files.

try {
  int x = 10 / 0;
} catch (Exception e) {
  System.out.println("An error occurred: " + e.getMessage());
} finally {
  System.out.println("The 'finally' block is executed regardless of whether an exception is thrown.");
}

Using finalize

In fact, the finalize() method in Java is a protected method available in the Object class, which is the parent class of all classes in Java. Actually, the Java garbage collector calls the finalize() method just before an object is garbage collected. So, it provides an opportunity to release any resources held by the object. The following example demonstrates the use of finalize() method to print a message when an object is finalized.

public class ExampleClass {
   protected void finalize() {
      System.out.println("Finalizing ExampleClass object");
   }
}

Further Reading

Java Practice Exercise

programmingempire

Princites