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

Final modifier:

  • The class cannot have descendants;
  • The method cannot be overridden in inherited classes;
  • The field cannot change its value after initialization;
  • Local variables cannot be changed once a value has been assigned to them;
  • Method parameters cannot change their value inside a method.

The finally statement guarantees that the specified section of code will be executed regardless of what exceptions were thrown and caught in the try-catch block.

The finalize() method is called before the garbage collector performs object disposal.

Example:

public class MainClass {

    public static void main(String args[]) {
        TestClass a = new TestClass();
        System.out.println("result of a.a() is " + a.a());
        a = null;
        System.gc(); // Forcibly call the garbage collector
        a = new TestClass();
        System.out.println("result of a.a() is " + a.a());
        System.out.println("!!! done");
    }

}

public class TestClass {

    public int a() {
        try {
            System.out.println("!!! a() called");
            throw new Exception("");
        } catch (Exception e) {
            System.out.println("!!! Exception in a()");
            return 2;
        } finally {
            System.out.println("!!! finally in a() ");
        }
    }

    @Override
    protected void finalize() throws Throwable {
        System.out.println("!!! finalize() called");
        super.finalize();
    }
}

Execution result:

!!! a() called
!!! Exception in a()
!!! finally in a() 
result of a.a() is 2
!!! a() called
!!! Exception in a()
!!! finally in a() 
!!! finalize() called
result of a.a() is 2
!!! done


Read also:


Comments

Popular posts from this blog

Methods for reading XML in Java

XML, well-formed XML and valid XML

ArrayList and LinkedList in Java, memory usage and speed