Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java

The difference between final, finally, and finalize in Java

Educative Answers Team

In Java, the words final, finally, and finalize are quite different from each other.

final

final is a keyword that is used to apply restrictions on a class, method, or variable.

  • The class with this keyword cannot be inherited.
  • The method with this keyword cannot be overridden.
  • The variable with this keyword cannot be changed.

Code

When we try to modify the value of the final variable val in the code below, ​it throws an error.

class HelloWorld {
    public static void main( String args[] ) {
        final int val=150;  
        val=100;
    }
}

finally

In Java, finally is a block used to place important code that will be executed whether or not an exception is handled.

Code

class HelloWorld {
    public static void main( String args[] ) {
      try{  
      int val=150;  
      }catch(Exception e){System.out.println(e);}  
      finally{System.out.println("finally block!");}
    }
}

finalize

finalize() is used to perform clean-up processing just before the object is collected by the garbage collector. In Java, the finalize method in a class is used for freeing up the heap’s memory, just like destructors in C++.

Note: finalize is deprecated in Java 9.

Code

class HelloWorld {
    public static class test
    {
        int val = 50;
        @Override
        protected void finalize() throws Throwable
        {
            System.out.println("Finalize Method");
        }
    }
   public static void main(String[] args)
   {
      test a1 = new test();
      test a2 = new test();

      a1 = a2;

      // calling finalize method
      System.gc(); 
   }

}

RELATED TAGS

java
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring