Variable textbook series (seven) - Java in the final modification of variables

Variable textbook series (seven) - Java in the final modification of variables

More, click here to learn, sign up for

final modification of a variable, there are a lot of stories, such as can not be changed, and so
accurate description is that when a final variable is modified, the opportunity for the variable assignment only once
Step 1: When an assignment statement
Step 2: When in a statement no assignment
step 3: final modification other

Example 1: When the assignment statement
i in the 4th line has already been assigned, so here compilation error occurs

public class HelloWorld {
 
    public void method1() {
        final int i = 5;
         
        i = 10; //i在第4行已经被赋值过了,所以这里会出现编译错误
         
    }
 
}

Example 2: When there is no assignment statement
if the statement when unassigned, you can assign a unique code behind

public class HelloWorld {
 
    public void method1() {
        final int i;
         
        i = 10; //i在第4行,只是被声明,但是没有被赋值,所以在这里可以进行第一次赋值
         
        i = 11; //i在第6行已经被赋值过了,所以这里会出现编译错误
         
    }
 
}

Example 3: final modify other
final addition to modification of variables, classes can also be modified, modification methods, which are deployed in the subsequent chapters

Published 32 original articles · won praise 182 · views 10000 +

Guess you like

Origin blog.csdn.net/weixin_44092440/article/details/102967614