Home Java JavaInterview questions Interviewer: Please explain in detail the role of the final keyword and its difference from static

Interviewer: Please explain in detail the role of the final keyword and its difference from static

Mar 08, 2021 am 10:27 AM
final static Keywords interview

Interviewer: Please explain in detail the role of the final keyword and its difference from static

Preface:

As expected, the interviewer asked this question again in the last interview: Could you please tell me the specific meaning of the final keyword and explain it in detail? Explain its function and its difference from static. In order to make everyone who is interviewing pay attention to this question, the answers are specially compiled for your reference.

1. The meaning of the final keyword

The surface meaning of final is that it cannot be changed, which means constant; similar to the const keyword in C language, it means that it cannot be changed. Quantity, which is different from static scalar. Static variables refer to only one storage space and the value can be changed. The reason for using final is from the perspective of software design, because when others see the keyword final, they will know what it means and achieve the effect of understanding it. However, it is precisely because of the existence of this "semantics" that you must be cautious in programming. Use to avoid misuse.

In Java, final modifications are constants, and variable names must be capitalized;

Math class: public static final double E = 2.7182818284590452354; public static final double PI = 3.14159265358979323846;
. .....Many variables in the java source code are modified with final

2. The role of final

The role of final is different depending on the position of the modification, for three situations:

(1) Modify variables. Variables modified by final must be initialized and cannot be reassigned after the initial value is assigned.

Note: Local variables are not within the scope of our discussion, because local variables themselves have scope and are not modified with words such as private and public.

(2) Modified method, the method modified by final means that it cannot be rewritten.

(3) Modified classes. Classes modified by final cannot be inherited.

Note: For a final-modified class, all member methods in the class are implicitly designated as final methods.

2.1. Final modified variables

Variables modified by final must be initialized explicitly. Initialization can be done in three ways: 1) initialized when defined, 2) set in the constructor Value, 3) Set the value for the final instance variable in the non-static block.

Final modified variable means: this variable cannot be changed after it is initialized. The immutable meaning here means that its value is immutable for basic types, and for object variables, its reference is immutable, that is, Can no longer point to other objects.

public class Test01{    
    final int x1= 10000;    
    final int x2;    
    final int x3;
    {
       x2 = 20000;
        }
    Public exe3(){        
        this.x3 = 3000;
        }
}
Copy after login

If the variable modified by final is an object type, then unchangeable means that the variable cannot point to other objects, but the value of the object can be changed, for example:

final Operate operate = new Operate() ;// operate有一个普通变量i初始化为10operate.i = 11;
operate.i = 12;
System.out.println(operate.i); //输出12上述是自定义类,即便是数组,List等集合类型,所保存的值也是可以更改的。
Copy after login

3. The difference between final and static

static acts on member variables to indicate that only one copy is saved, while final is used to ensure that variables are immutable. Take a look at an example on the Internet:

public class Test {
    public static void main(String[] args)  {
        MyClass myClass1 = new MyClass();
        MyClass myClass2 = new MyClass();
        System.out.println(myClass1.i);
        System.out.println(myClass1.j);
        System.out.println(myClass2.i);
        System.out.println(myClass2.j);
 
    }
}
class MyClass {
    public final double i = Math.random();
    public static double j = Math.random();
}
//运行结果,两次打印,j的值都是一样的,j是static类型的属于类,因此两次值相同。i不是static的因此属于对象,但是i的值是不可变的。
Copy after login

(Learning video sharing: java video tutorial)

4. Other final related knowledge

(1) Use the final keyword, if compiled If the compiler can determine the value of a variable during the compilation phase, the compiler will use the variable as a compile-time constant. If this needs to be determined at runtime, then the compiler will not optimize the relevant code.

public class Test {    
    public static void main(String[] args)  {
        String a = "hello2";  
        final String b = "hello";
        String d = "hello";
        String c = b + 2;  
        String e = d + 2;
        System.out.println((a == c));
        System.out.println((a == e));
    }
}
    //final类型,在编译阶段能够确定值。
    //非final类型在编译阶段确定不了
    输出:
        true
        false
    public class Test {    
            public static void main(String[] args)  {
            String a = "hello2";  
            final String b = getHello();
            String c = b + 2;  
            System.out.println((a == c));
 
        }     
    public static String getHello() {        
        return "hello";
    }
}
//即便是final类型,编译阶段也确定不了值。输出false
Copy after login

(2) Be careful not to confuse final with finally, finalize(), etc.

(3) Declaring classes, methods, and variables as final can improve performance, so that the JVM has the opportunity to estimate and then optimize.

(4) The variables in the interface are all public static final.

Related recommendations: java interview questions and answers

Original link: http://www.cnblogs.com/liun1994/p/6691094.html

Original author: Suifenglangzi90

The above is the detailed content of Interviewer: Please explain in detail the role of the final keyword and its difference from static. 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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

Hot Topics

Java Tutorial
1653
14
PHP Tutorial
1251
29
C# Tutorial
1224
24
Let's talk about how to choose the best Node.js Docker image? Let's talk about how to choose the best Node.js Docker image? Dec 13, 2022 pm 08:00 PM

Choosing a Docker image for Node may seem like a trivial matter, but the size and potential vulnerabilities of the image can have a significant impact on your CI/CD process and security. So how do we choose the best Node.js Docker image?

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

How to solve cross-domain issues? A brief analysis of common solutions How to solve cross-domain issues? A brief analysis of common solutions Apr 25, 2023 pm 07:57 PM

Cross-domain is a scenario often encountered in development, and it is also an issue often discussed in interviews. Mastering common cross-domain solutions and the principles behind them can not only improve our development efficiency, but also perform better in interviews.

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

In-depth analysis of the role and usage of the static keyword in C language In-depth analysis of the role and usage of the static keyword in C language Feb 20, 2024 pm 04:30 PM

In-depth analysis of the role and usage of the static keyword in C language. In C language, static is a very important keyword, which can be used in the definition of functions, variables and data types. Using the static keyword can change the link attributes, scope and life cycle of the object. Let’s analyze the role and usage of the static keyword in C language in detail. Static variables and functions: Variables defined using the static keyword inside a function are called static variables, which have a global life cycle

Golang framework interview questions collection Golang framework interview questions collection Jun 02, 2024 pm 09:37 PM

The Go framework is a set of components that extend Go's built-in libraries, providing pre-built functionality (such as web development and database operations). Popular Go frameworks include Gin (web development), GORM (database operations), and RESTful (API management). Middleware is an interceptor pattern in the HTTP request processing chain and is used to add functionality such as authentication or request logging without modifying the handler. Session management maintains session status by storing user data. You can use gorilla/sessions to manage sessions.

One article to understand the singleton pattern in JavaScript One article to understand the singleton pattern in JavaScript Apr 25, 2023 pm 07:53 PM

The JS singleton pattern is a commonly used design pattern that ensures that a class has only one instance. This mode is mainly used to manage global variables to avoid naming conflicts and repeated loading. It can also reduce memory usage and improve code maintainability and scalability.

Selected Java JPA interview questions: Test your mastery of the persistence framework Selected Java JPA interview questions: Test your mastery of the persistence framework Feb 19, 2024 pm 09:12 PM

What is JPA? How is it different from JDBC? JPA (JavaPersistence API) is a standard interface for object-relational mapping (ORM), which allows Java developers to use familiar Java objects to operate databases without writing SQL queries directly against the database. JDBC (JavaDatabaseConnectivity) is Java's standard API for connecting to databases. It requires developers to use SQL statements to operate the database. JPA encapsulates JDBC, provides a more convenient and higher-level API for object-relational mapping, and simplifies data access operations. In JPA, what is an entity? entity

See all articles