×

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 String charAt() method

It returns the char value present in the string at the specified index. Here, index value can not be greater than length() -1. Syntax: public char charAt (int index) Parmeters It accepts only...

3 minutes read.

User Defined Custom Exceptions in Java

In this tutorial, we will discuss user-defined custom exceptions with examples. Introduction In Java, we have proactively characterised, Exception classes, for example, ArithmeticException, NullPointerException, ArrayoutOfBound and so on. These built-in exceptions are...

3 minutes read.

Mutable class in Java

A language for object-oriented programming is Java. Because this is an object-oriented language of programming, all of its mechanisms and methods are based on objects. Java has a concept of...

6 minutes read.

Shopping Bill in Java

Java Shopping Bill Here in this program, we are about to create a JAVA class called Products which will have some properties or attributes like prod_name (Product Name ), qty (quantity),...

4 minutes read.

Java Math log() Method

The log() method of Math class returns the natural logarithmic value for the specified double argument. Syntax: public static double log(double a) Parameters: The parameter ‘a’ represents the value. Return Value: The log() method returns the...

1 minute read.

Java Arrays Fill

We may use the Arrays.fill () function to fill a whole array or a subset of it. Arrays.fill () may fill both 2D and 3D arrays. Syntax: Arrays.fill(boolean[] fillArr, int fromIndex, int toIndex, boolean val )   Parameters: The array to be filled...

4 minutes read.

What is anagram in Java?

In this section will explain what an anagram is in Java and demonstrate how to determine whether or not a text is an anagram. In Java interviews, the anagram Java...

4 minutes read.

Zigzag Array in Java

In this tutorial, we discuss, what is zigzag array and its example. Even we will create the java program. In this program, we convert the simple array into a zigzag...

4 minutes read.

Java Open File

Java Desktop class give an open() strategy to open a filr. It has a place with a java.awt package. Work area execution is stage subordinate, so it is important to...

5 minutes read.

Java Integer lowestOneBit()

The lowestOneBit () method of Java Integer class returns an int value with at most a single one-bit, in the position of the lowest-order one-bit in the specified int value.  Syntax public...

2 minutes read.

How to create array of objects in Java

Java is an object-oriented programming language therefore everything in Java is based on objects and classes. Array is a data structure that holds data of similar type and dynamically creates...

4 minutes read.

Java String copyValueOf() method

copyValueOf() method returns a String that holds the character sequence of the character array. Syntax: copyValueOf(char[] data) Parameters: data : the character array i.e. String Returns: It returns a String that contains the characters of the...

2 minutes read.

Java String Inbuilt functions

There are different types of inbuilt functions available in the Java String class, all of them are listed below. Char chat At (int index)It outputs the character indicated by the index....

5 minutes read.

Number Pattern Programs in Java

Number Pattern Programs in Java: Number pattern programs are part of pattern programs. In the previous section, we have learned the approach to print the pattern program in Java. To...

6 minutes read.

Figurate Number in Java

There have been several uses for figurate or figural numerals throughout history. A number that may be expressed by regular, distinct geometric shapes with spaced evenly points is referred to...

4 minutes read.

Maximizing Profit in Stock Buy Sell in Java

In this tutorial, we will deal with a popular problem, a favourite of interviewers. The problem is named as Maximising profit in stock Buy Sell. we will see certain approaches...

6 minutes read.

Java Tokens

Classes and methods are included in the Java program. The procedures also provide the expressions and statements required to finish a specific operation. Tokens make up the sentences and expressions...

4 minutes read.

Java Flags Enum

In a programming language, enumerations represent a group of named constants.For instance; the four suits in a deck of playing cards could be the enumerators Club, Diamond, Heart, and Spade,...

3 minutes read.

Star Pattern Programs in Java

Star Pattern Programs in Java The star pattern programs in Java is the part of pattern programs in Java, which we discussed earlier. Right Triangle Star Pattern Filename: StarPatternExample.java public class StarPatternExample {              public static void...

4 minutes read.

Set Up the Environment in Java

The Java is regarded as the pure object-oriented programming language. The Java applications are first compiled into the byte-code and then run by using the JVM. The Java is the...

4 minutes read.