当前位置:网站首页>Differences among fianl, finally, and finalize

Differences among fianl, finally, and finalize

2022-07-06 13:39:00 Wake up duck, did you program today?

First of all, there is no essential relationship between the three , During the interview, we will check our understanding of this :

  • fianl

    fianl Is used to modify variables , decorator , Modifier class attribute , When it modifies variables , The reference of the variable is immutable, but the content of the address can be changed , When it modifies a class , This class cannot be inherited but can be overloaded , When it modifies class attributes , Subclasses cannot reassign this property , If the value is assigned, an error will be reported .

  • finally

Common words try catch finally in , Used in exception handling finally Perform any cleanup , Whether or not there are exceptions thrown and caught finally All statements in will execute

If try There are... In the code block return sentence ,return The statement must be executed last ,java There is an eternal rule in , The program is executed line by line from top to bottom , Once implemented return The whole method ends .

Let's look at a topic :

package com.ws;

public class Demo02 {
    public static void main(String[] args) {
        int result = m();
        System.out.println(result);
    }

    public static int m(){
        int i = 100;

        try{
            return i;
        }finally {
            i++;
        }
    }
}


What are the above output results ? I guess most people will say yes 101, But the answer is 100

Let's take a look at the decompiled code

// The following is the decompiled code 
public static int m(){
    int i = 100;
    int j = i;
    i++;
    return j;

    Exception exception;
    exception;
    i++;
    throw exception;
}

The first is to put i The value of j, then i++( Is to perform fianlly Code inside ), Then return j.

  • finalize

In garbage collection , If the recycled object overrides finalize() Method , And in finalize() Method to re-establish the object and GC ROOT The connection of , Then the object can be resurrected once , That is, the object will return to the application stage from the collection stage .

The above is the difference between the three !!!

原网站

版权声明
本文为[Wake up duck, did you program today?]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207060916452607.html