The difference between final, finally, finalize in Java

Source: Internet
Author: User
Tags throwable






Java in the final, finally, finalize the difference and usage, troubled a lot of learners, the following we have some discussion on this issue, I hope that everyone's learning has helped.




Method/Step

Simple difference:


Final is used to declare properties, methods, and classes, respectively, that the property is non-alternating, that the method is not overridden, and that the class is not inheritable.


Finally is part of the exception-handling statement structure, which indicates that it is always executed.


Finalize is a method of the object class that, when executed by the garbage collector, invokes this method of the reclaimed object for other resources at garbage collection, such as closing the file.


END

Method/Step 2

Medium difference:


Although these three words exist in Java, there is not much association:


final : Keywords in Java, modifiers.




     1. If a class is declared final, it means that it can no longer derive a new subclass and cannot be inherited as a parent class. Therefore, a class cannot be declared at the same time as the Absrtact abstract class and the final class.


      2. If you declare variables or methods as final, you can guarantee that they will not be changed in use.


                2.1   A variable declared as final must be given an initial value at the time of declaration, and can only be read in subsequent references and cannot be modified.  


                The  2.2 declared final method can only be used and cannot be overloaded.

An exception handling mechanism for Finally:java.




Finally is the best complement to the Java exception handling model. The finally structure makes the code always executes, regardless of whether or not an exception occurs. Use finally to maintain the internal state of an object and to clean up non-memory resources. Especially in the case of shutting down the database connection, if the programmer puts the close () method of the database connection in the Finally, it will greatly reduce the chance of the program error.

A method name in the Finalize:java.




Java technology uses the Finalize () method to do the necessary cleanup work before the garbage collector clears objects from memory. This method is called by the garbage collector to this object when it determines that the object is not referenced. It is defined in the object class, so all classes inherit it. Subclasses override the Finalize () method to organize system resources or perform other cleanup work. The Finalize () method is called on the object before the object is deleted by the garbage collector.




END


Method/Step 3

Detailed differences:


This is a classic interview problem, we can almost see it in the interview questions of various companies. Final, finally, and finalize are like twin brothers, but their meanings and usages are quite different. This time we are going to look back on this knowledge.




1.final Keywords we first say final. It can be used in the following four places: 1.     Define variables, including static and non-static.     2. Define the parameters of the method.     3. Define the method. 4. Define the class. Let's review the final role in each case in turn.






1.1 Define variables, including static and non-static. Defining parameters for a method






First case:






If the final decoration is a basic type, it means that the value given by the variable is immutable, that is, it is a constant;






If the final decoration is an object, it means that the reference to which the variable is given is immutable.






It is important to note that what is immutable is only the reference to which the variable is stored, not the object that the reference refers to.












Second case:






Final means the same as in the first case.












In fact, in the first two cases, there is a more appropriate description of the final meaning, that is, if a variable or method parameter is final decorated, it means that it can only be assigned once, but the Java Virtual machine set the default value of the variable is not recorded once assignment.






The final modified variable must be initialized. There are several ways to initialize: 1.     Initialized at the time of definition.     2. The final variable can be initialized in the initialization block and cannot be initialized in a static initialization block.     3. A static final variable can be initialized in a static initialization block and cannot be initialized in the initialization block. 4. The final variable can also be initialized in the class's constructor, but the static final variable is not available.






The following code can be used to verify the above view:












Java code public class Finaltest {//initializes public final int A = 10 when defined;












Class in the initialization block.






public final int B;     {B = 20; }






A non-static final variable cannot initialize//public final int C in a static initialization block;     static {//C = 30; // }






Static constants, when defined, initialize public static final int static_d = 40;












Static constants, initialized in static initialization blocks






public static final int static_e;     static {static_e = 50; }






Static variables cannot be initialized in the initialization block//public static final int static_f;     {//static_f = 60; // }






public final int G;






Static final variables cannot be initialized in the constructor//public static final int static_h; Initializes public finaltest () {G = 70 in the constructor;






Static final variables cannot be initialized in the constructor






Static_h = 80;












The compilation will give an error when the final variable is assigned the second time






A = 99;






Static_d = 99;






}






Final variable not initialized, error at compile time






public final int I;






Static final variable not initialized, error at compile time






public static final int static_j;






}


















When we run the above code, we can see that the final variable (constant) and the static final variable (static constant) are initialized, and the compilation will give an error.












The final modified variables (constants) are more efficient than non-final variables (ordinary variables), so we should use constants as much as possible instead of ordinary variables in the inter programming, which is also a good programming habit.












1.2 Defining a method what is the effect when final is used to define a method? As you know, it means that this method cannot be overridden by a quilt class, but it does not affect its quilt class inheritance. Let's write a piece of code to verify:












Java Code public class parentclass {     public final void  testfinal ()  {          system.out.println (" Parent Class-This is a final method ");     }}public class subclass extends  parentclass {     /**     *  Subclasses cannot override (override) The final method of the parent class, or the compilation will error      */     //  Public void www.gzlij.com testfinal ()  {     // system.out.println (" Subclass--Overriding the final method ");     // }     public static  Void main (String[] args)  {          subclass  sc = new subclass ();           sc. Testfinal ();      }}












The special note here is that a method with private access can also increase the final decoration, but it cannot be overridden because the child cannot inherit the private method. The compiler treats the private method as if it were the final party, which can improve the efficiency of the method when it is called. However, subclasses can still define methods that have the same structure in the private method of the half, but this does not produce the effect of rewriting, and there is no necessary connection between them.












1.3 Defining classes






Finally, let's review the final case for classes. This people should also be familiar with, because our most commonly used string class is final. Because the final class is not allowed to be inherited, the compiler treats all its methods as final when it is processed, so the final analogy is more efficient than the ordinary class. Abstract classes, defined by the keyword abstract, contain an abstract method that must be implemented by a subclass overload that inherits from it, so the same class cannot be decorated with both final and abstract. In the same sense, final cannot be used to modify interfaces. None of the methods of the final class can be overridden, but this does not mean that the value of the final class's property (variable) is immutable, and to make the final class's property value immutable and must be added to the final decoration, see the following example:


















Java code Public final class Finaltest {






int i = 10;






final int j = 50;






public static void Main (string[] args) {






Finaltest ft = new Finaltest ();






FT.I = 99; The property value I of the final class Finaltest can be changed because the property value I is not in front of the final fix//






FT.J = 49; Error.... Because the J attribute is final, it cannot be changed.






System.out.println (FT.I);






}






}






Try running the above code, and the result is 99 instead of 10 at initialization time.


















2.finally statements






Let's review the use of finally in the next step. This is relatively simple, it can only be used in the Try/catch statement and accompanied by a block of statements, indicating that the sentence is always executed. Take a look at the following code:












Java code Public final class Finallytest {






public static void Main (string[] args) {






try {






throw new NullPointerException ();






} catch (NullPointerException e) {






SYSTEM.OUT.PRINTLN ("The program throws an exception");






} finally {






There will always be execution, unaffected by Break,return. Another example of a database connection close () is written here, which reduces the chance of a program's error






SYSTEM.OUT.PRINTLN ("finally statement block executed");






}






}






}


















The running results illustrate the role of finally: 1. The program throws an exception of 2. Execute the FINALLY statement block please note that after the exception thrown by the capture program, neither processing nor continuing to throw an exception, is not a good programming habit, it masks the execution of the program error, here is just a handy demonstration, please do not learn.






So, is there a situation where the finally statement block is not executed? You might have thought of it.












Return, continue, and break are the three rules that can disrupt the execution of a statement in code order. Let's see if these three statements will affect the execution of the finally statement block:












Java code Public final class Finallytest {






Test Return statement






The result is that the compiler compiles return new Returnclass (), dividing it into two steps, new Returnclass () and return, before the statement that created the object was executed before the finally statement block. The next return statement is executed after the finally statement block, which means that the finally statement block is executed before the program exits the method






Public Returnclass Testreturn () {






try {






return new Returnclass ();






} catch (Exception e) {






E.printstacktrace ();






} finally {






System.out.println ("A finally statement executed");






}






return null;






}












Test Continue statements






public void Testcontinue () {






for (int i = 0; i < 3; i++) {






try {






System.out.println (i);






if (i = = 1) {






Continue






}






} catch (Exception e) {






E.printstacktrace ();






} finally {






System.out.println ("A finally statement executed");






}






}






}












Test break statement






public void Testbreak () {






for (int i = 0; i < 3; i++) {






try {






System.out.println (i);






if (i = = 1) {






Break






}






} catch (Exception e) {






E.printstacktrace ();






} finally {






System.out.println ("A finally statement executed");






}






}






}












public static void Main (string[] args) {












Finallytest ft = new Finallytest ();












Test Return statement






Ft.testreturn ();






System.out.println ();












Test Continue statements






Ft.testcontinue ();






System.out.println ();












Test break statement






Ft.testbreak ();






}






}class Returnclass {public returnclass () {System.out.println ("executed return statement"); }}
























The result of this code is as follows: 1. A return statement of 2 was executed. A finally statement 3.4.05 was executed. The finally statement 6 was executed. 17. The Finally statement 8 is executed. 29. The finally statement 10.11 is executed. 012. The Finally statement 13 is executed. 114. Execute the Finally statement






























It is clear that return, continue, and break have failed to prevent the execution of the finally statement block. From the result of the output, the return statement appears to have been executed before the finally statement block, is that really the case? Let's think about it, what is the function of the return statement? is to exit the current method and return the value or object. If the finally statement block is executed after the return statement, then the return statement is executed and the current method is exited, and how can the finally statement block be executed? Therefore, the correct order of execution should be this: The compiler compiles the return new Returnclass (); When it is divided into two steps, new Returnclass () and return, the previous statement that created the object is in the finally statement block






Before a return statement is executed after the finally statement block, which means that the finally statement block is executed before the program exits the method. Similarly, the finally statement block is executed before the loop is skipped (continue) and interrupted (break).












3.finalize Method Finally, let's take a look at Finalize, which is a method that belongs to the Java.lang.Object class, which is defined as follows: Java code protected void Finalize () throws Throwable {} It is well known that the Finalize () method is part of the GC (garbage collector) operation mechanism. So let's just say what the Finalize () method does. The Finalize () method is called when the GC cleans up its subordinate objects, and if an uncaught exception (Uncaught exception) is thrown during its execution, the GC terminates cleanup of the modified object, and the exception is ignored, until the next time the GC starts cleaning up the object, Its finalize () will be called again. Take a look at the following example:












Java code Public final class Finallytest {






Overriding the Finalize () method






protected void Finalize () throws Throwable {






SYSTEM.OUT.PRINTLN ("Implementation of the Finalize () method");






}






public static void Main (string[] args) {






Finallytest ft = new Finallytest ();






FT = null;






System.GC ();






}






}


















The results of the operation are as follows: • Finalize () method executed






















The program calls the GC () method of the Java.lang.System class, causing the GC to execute, and the GC calls its finalize () method when the FT object is cleaned up, so that the output is the result. Calling System.GC () is equivalent to calling the following line of code: Java Code runtime.getruntime (). GC (); Calling them only suggests that the garbage collector (GC) starts and cleans up unused objects to free up memory space, but G's start-up is not certain. This is determined by the Java virtual machine. Until the Java virtual machine stops running, and some of the objects ' finalize () may not have been run, how do you ensure that this method of all objects must be called before the Java virtual machine stops running? The answer is that we can call another method of the system class:


Java code public static void Runfinalizersonexit (Boolean value) {//other code} passing in true to this method guarantees that the object's Finalize ()    The method must be run before the Java virtual machine stops running, but unfortunately this method is not secure, it causes the useful object Finalize () to be called incorrectly, and is therefore deprecated. Because Finalize () belongs to the object class, all classes have this method, and any subclass of object can override (override) The method, freeing the system resources or doing other cleanup work, such as shutting down the input and output stream. Through the above knowledge of the review, I think we have the final, finally, finalize the use of the difference is very clear.




The difference between final, finally, Finalize in Java (GO)




Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.