Final vs Finally vs Finalize

Definition of Final

“Final” is a keyword in Java. It is an access modifier. The “final” keyword is applicable to the classes, methods, and variables.

1) Final Variable

When a final keyword is applied to the variable, it can not be further modified. A final variable must be initialized when it is declared. In a common coding convention, final variables are declared in UPPERCASE. The final variable does not occupy memory on a per-instance basis.

Example

final int FILE_OPEN = 2;

Final Methods

When a method in a class, is declared as final, it can not be overridden by its subclass. Small methods that are declared final can be made “inline” by the compiler which will reduce the overhead of function calling and increase performance enhancements.

Overridden methods call, are resolved dynamically, but when a method is declared as final, it can not be overridden. Hence, the function call can be resolved at compile time.

Example

class  ClassA{

    final void meth() {

        System.out.println("This is a final method.");

    }

}

class ClassB extends ClassA {

    void meth() { // ClassB can not inherit the method of class A.

        System.out.println("Can't inherit because method is final in classA");

    }

}

Final Class

When a class is declared as final, then it can not be inherited by any subclass.

Declaring a class as final will automatically declare all its methods final.

You can not declare a class as both “abstract” and “final”.

Example

final class A {

    // ...

}

class B extends A { // Class B can not inherit class A
    // ...

}


Definition of Finally

In Java “finally” is a block that is always associated with the try/catch block. The “finally” block executes after the try/catch block and before the code following the try/catch block. The “finally” block will execute whether the exception is thrown or not.

When an exception is thrown, and no catch block matches the exception even then, the “finally” block is executed.

When a method returns to the caller from inside the try/catch block via an uncaught exception or an explicit return statement, the “finally” block gets executed just before the method returns to the caller.

The “finally” block is used to clean up the resources or free the memory used in the “try” block.

The “finally” block is optional, but it is a good practice to write the finally block after the try/catch block.

Example 1: Throw an exception out of the method.

public class ExceptionFinally {
    public static void main(String[] args) {

        method1();
    }

    static void method1() {

        try {

            System.out.println("inside method1");
            throw new RuntimeException("demo");

        } finally {
            System.out.println("method1 finally");

        }

    }
}

Output

inside method1 method1 finally Exception in thread "main" java.lang.RuntimeException: demo at com.prac.ExceptionFinally.method1(ExceptionFinally.java:14) at com.prac.ExceptionFinally.main(ExceptionFinally.java:6)


Example 2: Return from within a try block.

public class ExceptionFinally {
    public static void main(String[] args) {

        method2();
    }

    static void method2() {
        try {

            System.out.println("inside method2");
            return;

        } finally {
            System.out.println("method2 finally");

        }

    }
}

Output

inside method2 method2 finally


Example 3: No exception is thrown.

public class ExceptionFinally {
    public static void main(String[] args) {

        method3();
    }

    static void method3() {

        try {

            System.out.println("inside method3");

        } finally {

            System.out.println("method3 finally");

        }

    }
}

Output:

inside method3 method3 finally


Definition of Finalize

Finalize is a method in an object class.

An object may be holding some non-java resources such as a file handle; then it must be freed before it is destroyed.

This method is invoked by the garbage collector before it destroys the object completely.

This method performs cleanup activities for the object before it is destroyed.

The general form of the method finalize() is as follows.

Example

protected void finalize( )
{
// finalization code here
}


The finalize method is declared as protected so that it can not be accessed from outside the class. This method is always called before garbage collection.

Example

public class FinalizeMethod {
    public static void main(String[] args) {
        @SuppressWarnings("unused")
        FinalizeMethod finalizeMethod = new FinalizeMethod();
        finalizeMethod = null;
        System.gc();
        System.out.println("Main method");
    }

    // Here overriding finalize method
    public void finalize() {

        System.out.println("finalize method called");
    }
}

Output:

finalize method called Main method


Some of the differences between final, finally and finalize.

Final:

1) Final is a "Keyword" and "access modifier" in Java. Final is a keyword applicable to classes, variables, and methods.

2) Final variable becomes constant, and it can't be reassigned.

3) A final method can't be overridden by the child class.

4) Final Class can not be extended.

5) Final method is executed upon its call.

Finally:

1) Finally is a "block" in Java. Finally is a block that is always associated with try and catch block.

2) In a "finally" block, clean up the resources used in the "try" block.

3) "Finally" block executes just after the execution of the "try-catch" block.

Finalize:

1) Finalize is a "method" in Java. finalize() is a method applicable to objects.

2) Finalize method performs cleans up activities related to the object before its destruction.

3) finalize() method executes just before the destruction of the object.

Note:

1) The keyword final is an access modifier, finally is a block, and finalize is a method. The keyword final is applicable to the classes, variables, and methods of the classes finally is a block associated with the try-catch block that is used to handle exceptions, and finalize is a method that operates only on objects.

2) The variable once declared as final becomes constant and can’t be reassigned again, a method declared as final can’t be overridden, and a class once declared as final can never be inherited.

3) Finally block is used to clean up the resources utilized by the try-catch block. The finalized method is used to clean up the resources used by an object before the object is destroyed.


Exception Handling Using Throws keyword

Java try/ catch block exception handling

Java catches Multiple Exceptions

Exception Handling Using Throw keyword

Java nested try block exception handling

Java custom exception handling

Throw vs throws

Java finally blocks exception handling

Java Exception propagation

Final vs Finally vs Finalize

Exception Handling Interview Questions


No comments:

Post a Comment