“This article has participated in the call for good writing activities, click to view: the back end, the big front end double track submission, 20,000 yuan prize pool waiting for you to challenge!”

preface

The final keyword in Java is the final keyword.

Final means to be final and unchangeable. In Java, the final keyword can be used to modify variables, methods, and classes. Whatever it is, it’s meant to mean “it can’t be changed.” That’s what we need to keep in mind. Why not? Knowing how to use the final keyword is a matter of keeping in mind the immutable design concept of final as needed or needed to improve efficiency.

The body of the

Modify variables

Let’s start with an example

    public static void main(String[] args) {
        String a = "hello1";
        final String b = "hello";
        String d = "hello";
        String c = b + 1;
        String e = d + 1; System.out.println(a == c); System.out.println(a == e); }}Copy the code

Output result:

true
false

Process finished with exit code 0
Copy the code

Why do we get this? Let’s break it down:

  1. The variable A refers to the string constant poolhello1;
  2. The value of variable B is determined at compile time. In other words, the contents of variable B are known in advance, which is equivalent to a compile-time constant.
  3. The variable c is derived from b + 1. Since b is a constant, using b is directly equivalent to using the original value of BhelloSo c also generates a constant, a is a constant, c is a constant, bothhello1In Java, only one constant pool is generatedhello1String, so a and C are equal;
  4. D is pointing to the constant poolhelloHowever, since d is not final, which means that the value of d is not known in advance, the calculation of e is different. Since e is evaluated by reference to D, the variable d needs to be linked at runtime, so this calculation is generated on the heaphello1So eventually, e is going to be on the heaphello1, so a and E are not equal.

Conclusion: A and C are constant poolhello1E is on the heaphello1.

Variables modified by the final keyword are called constants, which means they cannot be changed. Variables are basic data types that cannot be changed and are easy to understand

You can see that base variables are immutable with final

What about reference types? Is it impossible to change its reference address, or the object’s content?

We first construct an entity class: Student

public class Student {

    private String name;

    public Student(String name){
        this.name = name;
    }

    public String getName(a) {
        return name;
    }

    public void setName(String name) {
        this.name = name; }}Copy the code

Create a Person object as follows:

The reference type of the final modifier cannot change the reference address of the object p. The reference type of the final modifier cannot change the address of the reference.

Next we change the name property of the p object:

Found that the program did not report errors, output results are small army

Conclusion: Variables decorated with final cannot change their reference address, but they can change their internal properties.

Modification methods

Methods decorated with the final keyword cannot be overridden.

The final method is used for two reasons:

  1. The first reason is to lock the method to prevent any inherited classes from changing its meaning for design reasons: you want to ensure that the behavior of the method remains the same in inheritance and is not overwritten.

  2. The second reason is efficiency. In early Implementations of Java, declaring a method final allowed the compiler to convert all calls to that method to inline calls. Inline calls made method calls more efficient, but did not improve performance if the method was large. In the current version of Java (after JDK1.5), virtual machines can be automatically optimized without the need for final methods.

So the final keyword is used only when it explicitly disallows overwriting methods.

PS: Ideas for Java programming states that all private methods ina class are implicitly final, so declaring them final explicitly has no effect. But if we create a parent class and declare a private method in the parent class, its subclass can override the private method of its parent class. Why?

The parent class: the Teacher. The class

public class Teacher {

    private void study(a){
        System.out.println("teacher"); }}Copy the code

Subclasses: Student in the class

public class Student extends Teacher{

    private void study(a){
        System.out.println("student"); }}Copy the code

In fact, if you look closely, is this method overwritten? We can’t call the parent say() method with polymorphic form:

Also, if we add the @override annotation to our subclass’s say() method, we’ll get an error.

So this is not an overlay of the method.

Methods modified by final cannot be overridden by subclasses, but can be used and overridden by subclasses.

Parent: A.c lass

public class A {

    public int a = 0;

    public int getA(a) {
        return a;
    }

    public final void setA(int a) {
        System.out.println("before set:A = " + this.a);// This must be added, otherwise the passed a will be used
        this.a = a;
        System.out.println("after set:A = "+ a); }}Copy the code

Subclasses: biggest lass

public class B extends A {

    public B(a) {
        super.setA(2);// The final method of the parent class can be used
        setA();// Call the class's own methods
    }

    public final void setA(a) {
        System.out.println("before set:super a = " + a);
        super.a++;
        System.out.println("after set:super a = "+ a); }}Copy the code

Test it out:

   public static void main(String[] args) {
        B b = new B();
    }
Copy the code

Output result:

before set:A = 0
after set:A = 2
before set:super a = 2
after set:super a = 3

Process finished with exit code 0
Copy the code

Conclusion: Methods decorated with the final keyword cannot be overridden, but can be used and overridden by subclasses.

decorator

A final modifier class indicates that the class cannot be inherited.

  1. That is, when you don’t want a class to have subclasses, use the final keyword. And because a class is final, all methods in its class are implicitly referred to as final methods.

  2. One of the most obvious classes in the JDK, String, is modified with final, and one reason it’s important to modify String with final is constant pools.

eggs

What is the difference between Final, finally and Finalize?

finally

The finally keyword is usually used in exceptions. It is used in conjunction with a try catch to indicate that the content in finally must be executed regardless of whether an exception occurs.

1. Order of execution when a try contains a return

A return statement is not the final exit of a function. If there is a finally statement, finally is executed after the return. (The value of the return is temporarily stored on the stack until finally is executed.)

Return and exception get the position of the statement

  1. Case 1 (return in try, no return in finally)
public class TryTest {

    public static void main(String[] args) {
        System.out.println(test());
    }

    private static int test(a) {
        int num = 10;
        try {
            System.out.println("try");
            return num += 80;
        } catch (Exception e) {
            System.out.println("error");
        } finally {
            if (num > 20) {
                System.out.println("num>20:" + num);
            }
            System.out.println("finally");
        }
        returnnum; }}Copy the code

Output result:

try
num>20:90
finally
90

Process finished with exit code 0
Copy the code

Analysis: Return num =num+80; return num =num+80; Execute the statement in finally first, and then return 90.

  1. Case 2 (return in both try and finally)
public class TryTest {

    public static void main(String[] args) {
        System.out.println(test());
    }

    private static int test(a) {
        int num = 10;
        try {
            System.out.println("try");
            return num += 80;
        } catch (Exception e) {
            System.out.println("error");
        } finally {
            if (num > 20) {
                System.out.println("num>20:" + num);
            }
            System.out.println("finally");
            return 100; }}}Copy the code

Output result:

try
num>20:90
finally
100

Process finished with exit code 0
Copy the code

Analysis: The return in the try is “overwritten” and will not be executed.

  1. Case 3 (no return in finally, but change return num in finally)
public class TryTest {

    public static void main(String[] args) {
        System.out.println(test());
    }

    private static int test(a) {
        int num = 10;
        try {
            System.out.println("try");
            return num;
        } catch (Exception e) {
            System.out.println("error");
        } finally {
            if (num > 20) {
                System.out.println("num>20:" + num);
            }
            System.out.println("finally");
            num = 100;
        }
        returnnum; }}Copy the code

Output result:

try
finally
10

Process finished with exit code 0
Copy the code

Analysis: The test () function returns the value of num ina try after executing a statement in finally, even though the return value of num is changed in finally. The value of num in the try is still the value reserved before the program entered the finally block, so the return value is 10. And the return statement at the end of the function is not executed.

  1. Case 4 :(wrap the num value in the num class)
public class TryTest {

    public static void main(String[] args) {
        System.out.println(test().num);
    }

    private static Num test(a) {
        Num num = new Num();
        try {
            System.out.println("try");
            return num;
        } catch (Exception e) {
            System.out.println("error");
        } finally {
            if (num.num > 20) {
                System.out.println("num.num>20:" + num.num);
            }
            System.out.println("finally");
            num.num = 100;
        }
        returnnum; }}class Num {
    public int num = 10;
}
Copy the code

Output result:

try
finally
100

Process finished with exit code 0
Copy the code

If the data ina return is a reference data type, and the change in finally affects the value of the reference data type, then the return statement ina try returns the value of the property changed in finally.

finalize

Finalize () is a method of the Object class, and Java technology runs using Finalize () to do the necessary cleanup before the garbage collector purifies objects from memory. This method is called when the garbage collector determines that the object has no references to it. The Finalize () method is a subclass called on an object before the garbage collector deletes it to overwrite the Finalize () method to clean up system resources or perform other cleanup operations.

public class FinalizeTest {

    public static void main(String[] args) {
        Person p =  new Person("Pony".55);
        p = null;// The Person object in the heap will have no variables to point to, and will become garbage, which will be output when Finalize () is called by garbage collection mechanismSystem.gc(); }}class Person {

    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    protected void finalize(a) throws Throwable {
        System.out.println("Execute Finalize () to recycle objects"); }}Copy the code

conclusion

Benefits of using the final keyword:

  1. Final methods are faster than non-final methods.
  2. The final keyword improves performance. Both JVM and Java applications cache final variables.
  3. Final variables can be safely shared in multi-threaded environments without additional synchronization overhead.
  4. With the final keyword, the JVM optimizes methods, variables, and classes.

At the end

I am a coder who is being beaten and still trying to move on. If this article is helpful to you, remember to like and follow yo, thanks!