search
HomeJavajavaTutorialFinal all-round in-depth analysis

Final all-round in-depth analysis

Jul 19, 2017 pm 01:14 PM
finalabout


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
    }
}

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
 
}

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");

    }

}

Running results:

Method with finals took 5 ms
Method without finals took 273 ms

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
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
How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

See all articles

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)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment