What are the uses of final, finally and finalize in java?

Answer Posted / javamasque

final: It is used to stop modifying further. It is used before class (top-level/inner), variable (class/instance) and method.
If class become final, it never be sub-classed.
If variable become final, it never be modified through the program or application.
If method become final, it never be override.

finally: It is used to release resources with try or try-catch block. It is always executed block irrespective of throw or return statement. It can be only stopped with infinite loop or System.exit(0). Previously file handling code used finally block to close InputStream or OutputStream object. Now finally block is not used to close these object. They are implicitly auto closed as they are implementing AutoClosable interface.

finalize(): As we override the protected finalize method to release resources. It is the final step where we can release resource (means either nullify the object or close the stream objects etc.). It is called before GC .But issue is the below points,
•There is no guarantee that it will be called or if called the resource will be released by GC immediately.
•We should not completely rely on this way of releasing memory.
•We can urge JVM to execute our finalize method with below statements but it has no guarantee that the objects will be freed immediately by GC.
System.runFinalization() OR Runtime.getRuntime().runFinalization()

Is This Answer Correct ?    5 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

Is null in java?

549


Explain about varargs in java?

583


Can a vector contain heterogenous objects?

594


Justify your answer that you can't define a method inside another method in java, if you can then how?

600


Is string pool garbage collected?

545






What are the new features in java 8?

568


How static variable work in java?

598


How many threads does a core java have?

509


What is a JAR file?

590


What is bom encoding?

554


Define how objects are stored in java?

563


Why is singleton instance static?

503


What is double in java?

514


Difference between Linked list and Queue?

606


Why heap memory is called heap?

584