×

Difference between final, finally, and finalize()

Difference between final, finally, and finalize()

In Java, final, finally and finalize sound similar they are totally different in functionality. Final and finally are the two keywords but the finalize is a method of the Object class. In this section, we will discuss the differences between final, finally, and finalize().

Java final keyword

final is a keyword in Java that means we cannot use final as an identifier in the Java program. When a class, method and a variable name is preceded with final keyword it means that they cannot be inherited by another class, the method cannot be overridden by another method, and the value assigned to the variable cannot be updated respectively.

Let’s use the final keyword with class, method, and variable in Java programs.

  1. Using final keyword with Class:

XYZ.java

 final class ABC
{
    /* Methods and variable can be declared here. */
}
/*Compile time error. XYZ can’t inherit ABC as it is final. */
public class XYZ extends ABC
{
    /* Driver Code */
    public static void main(String args[])
    {
    }
} 

          Output:

Difference between final, finally, and finalize()

The above code shows the use of final keyword with class ABC. Class XYZ cannot inherit class ABC as it is a final class.

  • Using final Keyword with Method

Sample.java

 public class Sample
{
           /* final method */
          final void test()
          {
              System.out.println("Inside test method"); 
          }
          /* Driver code */
          public static void main(String a[])
          {
              Sample s=new Sample();
              s.test();
          }
}
class PQR extends Sample
{
          /* Compile time error. Can't override test() because it is final. */
          void test() {}
} 

Output:

Difference between final, finally, and finalize()

The above code shows the use of final keyword with test() method declared inside Sample class. The method cannot be overridden in the child class PQR.

3. Using final Keyword with Variable:

Sample.java

 public class Sample
{
    /* Driver Code */
     public static void main(String a[])
     {
              // Simple variable
              int p = 5;
              // Variable with final keyword
              final int q = 6;
              /* modifying the simplevariable : Allowed */
              p++;
              /* Compile Time error. Can’t modify final variable*/
              q++;
     }
} 

Output:

Difference between final, finally, and finalize()

The above code shows the use of final keyword with variable qdeclared inside Sample class.

Java finally keyword

In Java, finally is a reserved keyword. It is used in exception handling. The finally block is always used after try-catch block.The finally block executes even if an unexpected exception occurs.Writing the cleanup code in a finally block is always a good practice, even when no exceptions are predicted.

FinallyExample.java

 public class FinallyExample
{
          /* methodOne()with try-catch and finally block. Called inside try-catch block in driver code */
          static void methodOne()
          {
                   try
                   {
                             System.out.println("Inside First try block");
                             throw new RuntimeException("e");
                   }
                   finally
                   {
                             System.out.println("Inside first finally");
                   }
          }
          /*Method called outside try-catch block in driver code.*/
          static void methodOne()
          {
                   try
                   {
                             System.out.println("Inside Second try block");
                             return;
                   }
                   finally
                   {
                             System.out.println("Inside second finally");
                   }
          }
          /* Driver Code */
          public static void main(String args[])
          {
                   try {
                             methodOne();
                   }
                   catch (Exception e) {
                             System.out.println("Exception caught");
                   }
                   methodTwo();
          }
} 

Output:

Difference between final, finally, and finalize()

The above code shows the use of finally block declared inside methodOne() and methodTwo() in the FinallyExampleclass.

Java finalize() method

In Java, the finalize() method is called by the garbage collector in order to free up the memory heap. It is called just before removing the unused objects. It is a method of the Object class. It is called when an object is dereferenced. The dereferenced object needs to be destroyed by the garbage collector.

FinalizeExample.java

 public class FinalizeExample
{
    @Override
          protected void finalize()
          {
                   System.out.println("finalize method executed");
          }
          /*Driver Code */
          public static void main(String a[])
          {
                   Sample h1 = new Sample();
                   h1 = null;      /* Marking h1 for garbage collection */
                    System.gc();    /*Garbage collector calls finalize */
                   System.out.println("Main completed");
          }
} 

Output:

 Main completed
finalize method executed 

The above code shows the use of finalize() method overridden inside FinalizeExample class.

Difference between final, finally, and finalize()

Sr. no.finalfinallyfinalize()
1.final is a keyword/access modifier.finally is a block used with try-catch block.finalize() is a protected method declared in java.lang.Object class.
2.Classes, variables, and methods are preceded by the final keyword.The try-catch block is followed by finally block. It is not necessary to use finally. But it is recommended to use finally block while handling an exception.finalize() method works on objects that are marked for garbage collection.
3.Using the final keyword implies restrictions on class, method, and variables. The class cannot be extended, the method cannot be overridden, variable value cannot be updated.finally block is used during exception handling. Even if try-catch block doesn’t execute, statements inside finally block will be executed.While using finalize() method, it should be overridden. It is used for garbage collection.
4.final method is executed when the programmer makes a call to it.finally block performs it’s execution after the try-catch block. finalize() method executes before garbage collector destroys the dereferenced objects.

In this article we have discussed final, finally and finalize() with examples. The key differences among themare also explained.


Related Topics

Java Font

The font is a Java class that is a part of java.awt package. The Serializable interface is implemented by it. The direct recognized child of a Java Font class is...

8 minutes read.

Various operations on the Queue using Stack in Java

The Java Collections Framework's core data structures are the Stack and Queue. They are used to store and retrieve identical data in a presentation sequence. These two linear data structures...

7 minutes read.

Java Program to Sort an Array of 0's, 1's, and 2’s | Dutch National Flag Problem in Java

The famed Dutch computer programmer Edsger Dijkstra's Dutch Nation Flag (DNF) challenge ranks among the most well-known programming challenges. The Dutch tricolor flag, comprising red, white, and blue, is the...

3 minutes read.

Even Odd Program in Java

Even Odd Program in Java The number that are completely divisible by 2 are even and the number that leaves remainder are odd numbers. For example, the numbers 2, 0, 4,...

5 minutes read.

Method Overloading In Java

If the same class consists of different methods with the same name and the methods can vary by different number of parameters then it is known as Method Overloading. Method...

2 minutes read.

Nested Enum in Java

A class that can be defined within another class is called a nested class in Java. You can logically group classes that are used onlyin one place. This makes encapsulation...

3 minutes read.

Sorting Program in Java

Sorting Program in Java: The sorting program in Java is used to sort arrays either in ascending or descending order.  There are two predefined methods available in Java that are...

6 minutes read.

Advanced Java skills

These were some of the contemporary talents that a Java developer should master in efforts to progress in the era of science in 2022. A database such as MySQL, a...

4 minutes read.

Narcissistic Number in Java

A Narcissistic number is made up of digits that have been added together and raised to powers equal to the number of digits in the original number. In those other...

3 minutes read.

Java Math multiplyFull() Method

The multiplyFull() method of Math class returns the exact product of the arguments. Syntax: public static long multiplyFull (int x, int y) Parameters: The parameters ‘x’ and ‘y’ represent the first value and second...

1 minute read.

Facts about null in Java

Nearly all programming languages have a relationship with null. Hardly any programmers are unconcerned by null. The null has a java.lang.NullPointerException association in Java. Given that it is a class...

4 minutes read.

Java TreeMap

TreeMap in Java with Example Java TreeMap implements the NavigableMap interface. It extends Map Interface. Java TreeMap is based on the red-black Tree implementation. It stores the key-value pair in sorted...

7 minutes read.

Java Image

For all other classes used for representing graphical images, Java's Image class serves as an abstract superclass. For images in Java, a specific form of object known as a BufferedImage...

4 minutes read.

Buffer reader to read string in Java

The Buffered Reader class of Java is used to read the stream of characters from the input stream. Program to read string using Buffer reader import java.io.*; class  Demo {   public static void main(String...

3 minutes read.

Java String replaceAll() method

Java String replaceAll() method returns a String replacing all the sequence of characters matching regular expression i.e regex and replacement string. Syntax: public String replaceAll(String regex, String replacement) Parameters: regex : regular expression replacement :...

1 minute read.

Java Break Keyword

Break: The word Break is a keyword or a statement in a java programming language.This Keyword break is used to stop the execution of the loop or switch statements etc.The loop...

3 minutes read.

Singleton class in Java

What is Singleton class in Java? Singleton means it is one. That means we can create only one instance or object of a class. For example, let us have a class...

3 minutes read.

Exception Handling Program in Java

Exception Handling Program in Java Exception means something that is abnormal. In Java, an exception is treated as a problem that disrupts the normal flow of the program. An exception leads...

7 minutes read.

Java callable example

What is callable in Java? Callable is an interface that is present in Java. There are two methods for constructing threads: one is to inherit the Thread class, while the other...

3 minutes read.

How many ways to create object in Java?

In this article, you will be acknowledged about the different ways to create an object in java. So far you construct an object from a class, as is common knowledge,...

6 minutes read.