Table of Contents
Effectively Final
Benefits of final
Use of final keyword
Summary
Home Java javaTutorial Final all-round in-depth analysis

Final all-round in-depth analysis

Jul 19, 2017 pm 01:14 PM
final about


Java has a keyword final. A variable can be declared as a final type. A final type variable can only be assigned once. If a final variable is assigned a value repeatedly, a compilation error will occur.


What is the meaning of the final keyword?

final is a reserved keyword in Java that can declare member variables, methods, classes and local variables. Once you make the reference declaration final, you will not be able to change the reference. The compiler will check the code and if you try to initialize the variable again, the compiler will report a compilation error.

What is a final variable?

Any member variables or local variables (variables in methods or code blocks are called local variables) that are declared final are called final variables. Final variables are often used with the static keyword as constants. The following is an example of a final variable:

public static final String LOAN = "loan";

LOAN = new String("loan") //invalid compilation error

final variable is read-only.

What is a final method?

Final can also declare methods. Adding the final keyword in front of a method means that this method cannot be overridden by methods of subclasses. If you think the function of a method is complete enough and does not need to be changed in subclasses, you can declare the method as final. Final methods are faster than non-final methods because they are statically bound at compile time and do not need to be dynamically bound at runtime. The following is an example of a final method:

class PersonalLoan{
    public final String getName(){
        return "personal loan";
    }
}
 
class CheapPersonalLoan extends PersonalLoan{
    @Override
    public final String getName(){
        return "cheap personal loan"; //compilation error: overridden method is final
    }
}
Copy after login

What is a final class?

A class modified with final is called a final class. Final classes are usually functionally complete and they cannot be inherited. There are many classes in Java that are final, such as String, Interger and other wrapper classes. The following is an example of the final class:

final class PersonalLoan{
 
    }
 
    class CheapPersonalLoan extends PersonalLoan{  //compilation error: cannot inherit from final class
 
}
Copy after login

Benefits of the final keyword

The following summarizes some of the key words to use final Benefits of words

The final keyword improves performance. Both JVM and Java applications cache final variables.

Final variables can be safely shared in a multi-threaded environment without additional synchronization overhead.

Using the final keyword, the JVM will optimize methods, variables and classes.

Effectively Final

A variable will be considered effectively if and only if it is in the following situations

1. Not declared as final

2 .The value is only assigned once

The simplest way to explaineffectively finalis to imagine that it has been modified with final. If modified in this way, the program will still run without error (when the compilation is passed) ^0^), and is consistent with the original running result, then this variable can be said to be effectively final.

Benefits of final

Restricting local variables to valid immutable variables is designed to allow developers to better handle concurrency and thread-safe development. Mutable fields are always a potential source of concurrency problems if not managed properly.

Use of final keyword

I think it is a good habit to declare variables, method parameters, etc. as final. It can be a good reminder to other people in the team not to modify it lightly. Put this aside, declare it as final, and the compiler will optimize it well when compiling it into a class file.

There are many arguments against "it is incorrect to use the final keyword in source files to achieve optimization of class files". It is strongly recommended to read Robert Simons Jr's "Hardcore Java 》Details on the use and optimization of final keywords.

In an application, the final keyword makes the intention of your code look obvious, and it will not be changed after the declaration, which is very safe.

public class FinalTest {

    public static final int N_ITERATIONS = 10_00_000;

    public static String testFinal() {
        final String a = "a";
        final String b = "b";
        return a + b;
    }

    public static String testNonFinal() {
        String a = "a";
        String b = "b";
        return a + b;
    }

    public static void main(String[] args) {
        long tStart, tElapsed;

        tStart = System.currentTimeMillis();
        for (int i = 0; i < N_ITERATIONS; i++)
            testFinal();
        tElapsed = System.currentTimeMillis() - tStart;
        System.out.println("Method with finals took " + tElapsed + " ms");

        tStart = System.currentTimeMillis();
        for (int i = 0; i < N_ITERATIONS; i++)
            testNonFinal();
        tElapsed = System.currentTimeMillis() - tStart;
        System.out.println("Method without finals took " + tElapsed + " ms");

    }

}
Copy after login

Running results:

Method with finals took 5 ms
Method without finals took 273 ms
Copy after login

Summary

Final can make the variables you declare safer and make your code safer It seems clearer, and Effective Java also advocates the use of immutable classes.


The above is the detailed content of Final all-round in-depth analysis. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

The difference between final, finally, and finalize in Java The difference between final, finally, and finalize in Java Feb 19, 2024 pm 12:16 PM

The difference between final, finally, and finalize in Java requires specific code examples. In Java programming, you often encounter the three keywords final, finally, and finalize. Although they are spelled similarly, they have different meanings and usages. This article will explain the differences between these three keywords in detail and give code examples to help readers better understand. 1. Final keyword The final keyword can be used for classes, methods and variables. Its function is to make the modified class

In Java, is it possible to define a constant using only the final keyword? In Java, is it possible to define a constant using only the final keyword? Sep 20, 2023 pm 04:17 PM

A constant variable is a variable whose value is fixed and only one copy exists in the program. Once you declare a constant variable and assign a value to it, you cannot change its value again throughout the program. Unlike other languages, Java does not directly support constants. However, you can still create a constant by declaring a variable static and final. Static - Once you declare a static variable, they will be loaded into memory at compile time, i.e. only one copy will be available. Final - Once you declare a final variable, its value cannot be modified. Therefore, you can create a constant in Java by declaring the instance variable as static and final. Example Demonstration classData{&am

What is the function of java final keyword What is the function of java final keyword Nov 25, 2022 pm 04:26 PM

In Java, final can be used to modify classes, methods and variables. The final modified class means that the class cannot be inherited by any other class, which means that this class is a leaf class in an inheritance tree, and the design of this class has been considered perfect and does not need to be modified or extended. The method in the final modified class means that the class cannot be inherited by any other class and cannot be overridden; that is, the method is locked to prevent the inherited class from changing it. final modifies a variable in a class, indicating that the variable cannot be changed once it is initialized.

How are final objects created in Java? How are final objects created in Java? Apr 11, 2024 pm 02:00 PM

There are two ways to create final objects in Java: declaring a final variable or declaring a class using the final modifier. When a final variable is declared, the object is created through an initializer; when a final class is declared, the class instance is immutable. Importantly, references to final objects can still change, but the objects they point to are immutable.

final variable in java final variable in java Sep 24, 2023 pm 08:49 PM

Final variables can only be explicitly initialized once. A reference variable declared as Final can never be reassigned to refer to a different object. However, the data within the object can be changed. Therefore, the state of the object can change, but the reference cannot. For variables, the final modifier is usually used with static to make the constant a class variable. Example publicclassTest{ finalintvalue=10; //Thefollowingareexamplesofdeclaringconstants: &a

ColorOS15 interface exposed. About this machine, here is a big change ColorOS15 interface exposed. About this machine, here is a big change Aug 28, 2024 pm 03:31 PM

Recently, ColorOS15 took the lead in launching internal beta testing. Some netizens exposed the relevant interface. Let’s see how it goes. As you can see in the picture above, some netizens posted the “About This Machine” interface of OPPO Find X7 after upgrading ColorOS15Beta. In addition to the big change in the top pattern, The configuration information in the lower half has also changed from the previous two columns to a single column vertical distribution. Attached is the "About This Phone/Mobile Phone" interface in the latest versions of mobile phones from six brands: Huawei, Honor, Xiaomi, OPPO, vivo, and Meizu. You can tell me which layout you like better. Regarding ColorOS 15, previous news said In addition to supporting LivePhoto live photos on a wide scale, it will also "support AirDrop&

ColorOS15 interface exposed. About this machine, here is a big change ColorOS15 interface exposed. About this machine, here is a big change Aug 28, 2024 pm 03:31 PM

Recently, ColorOS15 took the lead in launching internal beta testing. Some netizens exposed the relevant interface. Let’s see how it goes. As you can see in the picture above, some netizens posted the “About This Machine” interface of OPPO Find X7 after upgrading ColorOS15Beta. In addition to the big change in the top pattern, The configuration information in the lower half has also changed from the previous two columns to a single column vertical distribution. Attached is the "About This Phone/Mobile Phone" interface in the latest versions of mobile phones from six brands: Huawei, Honor, Xiaomi, OPPO, vivo, and Meizu. You can tell me which layout you like better. Regarding ColorOS 15, previous news said In addition to supporting LivePhoto live photos on a wide scale, it will also "support AirDrop&

Special syntax in PHP: Static, Final, Abstract and other keywords Special syntax in PHP: Static, Final, Abstract and other keywords May 11, 2023 pm 04:00 PM

PHP is a popular open source server-side scripting language widely used in web development. The PHP language is not only easy to learn and use, but also supports a variety of programming paradigms, object-oriented programming, functional programming, etc. In PHP, there are some special syntax keywords, such as Static, Final, Abstract, etc. These keywords have special functions in object-oriented programming. This article will introduce these keywords in detail. Static keyword In PHP, the Static keyword has two uses

See all articles