What is difference between final finally and finalize

What is difference between final finally and finalize

Answer: The keyword final have three uses. First, it can be used to create equivalent of a named constant and other two uses of final apply to inheritance. Example below:

Final variable: You can declare a variable as final. Doing so prevents its contents from being modified.
This means that you must initialize a final variable when it is declared. For example:

package com.javahonk.finalTest;

public class FinalTest {

    final int SUNDAY = 1;
    final int MONDAY = 2;
    final int TUESDAY = 3;
    final int WEDNESDAY = 4;
    final int THRUSDAY = 5;
    final int FRIDAY = 6;
    final int SATURDAY = 7;

}

 

Now class can use SUNDAY, MONDAY etc., as if they are constants, without fear that a value will be changed. By specification we should choose all uppercase identifiers for final variables. Variables declared as final do not occupy memory on a per-instance basis. Thus, a final variable is essentially a constant.

Final Methods: As we know method overriding is one of Java’s most powerful features, but there will be you would like to prevent it from occurring. To disallow a method from being overridden, specify final as a modifier at the start of its declaration. Once methods declared as final cannot be overridden. Example below:

package com.javahonk.finalTest;

public class DEF extends ABC {

    // Error: overrides com.javahonk.finalTest.ABC.methodTest
    // - Cannot override the final method from ABC
    final void methodTest() {
	System.out.println("This is a final method.");
    }

}

class ABC {
    final void methodTest() {
	System.out.println("This is a final method.");
    }
}

 

Because methodTest( ) is declared as final, it cannot be overridden in class DEF. If you try to do, a compile-time error will result.

Final Class: Often you will want to prevent a class from being inherited. To do so, precede the class declaration with final. Declaring a class as final implicitly declares all of its methods as final, too. As you might expect, it is illegal to declare a class as both abstract and final since an abstract class is incomplete by itself and relies upon its subclasses to provide complete implementations. final class example below:

package com.javahonk.finalTest;

//Below class is illegal.
class DEF extends ABC { // ERROR! Can't subclass ABC

}

final class ABC {
    // ...
}

 

Finally : finally creates a block of code that will be executed after a try/catch block has completed and before the code following the try/catch block. The finally block will execute whether or not an exception is thrown. If an exception is thrown, the finally block will execute even if no catch statement matches the exception. Any time a method is about to return to the caller from inside a try/catch block, via an uncaught exception or an explicit return statement, the finally clause is also executed just before the method
returns. This can be useful for closing file handles and freeing up any other resources that might have been allocated at the beginning of a method with the intent of disposing of them before returning. The finally clause is optional. However, each try statement requires at least one catch or a finally clause.

package com.javahonk.finalTest;

class DEF {
    public static void main(String args[]){
	methodTest();
    }

    static void methodTest() {
	try {
	    System.out.println("inside methodTest");
	    throw new RuntimeException("demo");
	} finally {
	    System.out.println("methodTest finally");
	}
    }
}

 

Output:

inside methodTest
methodTest finally
Exception in thread "main" java.lang.RuntimeException: demo
	at com.javahonk.finalTest.DEF.methodTest(DEF.java:11)
	at com.javahonk.finalTest.DEF.main(DEF.java:5)

 

Example 2: 

package com.javahonk.finalTest;

class DEF {
    // Through an exception out of the method.
    static void methodTest() {
	try {
	    System.out.println("inside methodTest");
	    throw new RuntimeException("demo");
	} finally {
	    System.out.println("methodTest finally");
	}
    }

    // Return from within a try block.
    static void methodTestB() {
	try {
	    System.out.println("inside methodTestB");
	    return;
	} finally {
	    System.out.println("methodTestB finally");
	}
    }

    // Execute a try block normally.
    static void methodTestC() {
	try {
	    System.out.println("inside methodTestC");
	} finally {

	    System.out.println("methodTestC finally");
	}
    }

    public static void main(String args[]) {
	try {
	    methodTest();
	} catch (Exception e) {
	    System.out.println("Exception caught");
	}
	methodTestB();
	methodTestC();
    }
}

 

Output: 

inside methodTest
methodTest finally
Exception caught
inside methodTestB
methodTestB finally
inside methodTestC
methodTestC finally

 

finalize : Sometimes an object will need to perform some action when it is destroyed. For example, if an object is holding some non-Java resource such as a file handle or character font, then you might want to make sure these resources are freed before an object is destroyed. To handle such situations, Java provides a mechanism called finalization. By using finalization, you can define specific actions that will occur when an object is just about to be reclaimed by the garbage collector.

To add a finalizer to a class, you simply define the finalize( ) method. The Java run time calls that method whenever it is about to recycle an object of that class. Inside the finalize( ) method, you will specify those actions that must be performed before an object is destroyed.
The garbage collector runs periodically, checking for objects that are no longer referenced by any running state or indirectly through other referenced objects. Right before an asset is freed, the Java run time calls the finalize( ) method on the object. Example below:

package com.javahonk.finalTest;

public class DEF {

    protected void finalize() {
	System.gc();
    }
}

 

Here, the keyword protected is a specifier that prevents access to finalize( ) by code defined outside its class. It is important to understand that finalize( ) is only called just prior to garbage collection. It is not called when an object goes out-of-scope, for example. This means that you cannot know when—or even if—finalize( ) will be executed. Therefore, your program should provide other means of releasing system resources, etc., used by the object. It must not rely on finalize( ) for normal program operation.

Leave a Reply

Your email address will not be published. Required fields are marked *

I am not Robot *