When you use final action on a member variable of a class, the member variable (note is the member variable of the class, the local variable needs to be guaranteed to be initialized before use) must be assigned in the definition or constructor, and once the final variable is initialized, it can no longer be assigned a value.
So what is the difference between a final variable and a normal variable? Let's take a look at the following example:
Public class Test { publicstaticvoid main (string[] args) { = "Hello2" ; Final String b = "Hello"; = "Hello"; = B + 2; = d + 2; = = c)) ; = = e));} }
true false
We can first think about the output of this problem. Why the first comparison result is true, and the second compares the result to Fasle. This is the difference between the final variable and the normal variable, when the final variable is the base data type and the string type, if you can know its exact value during compilation, the compiler will use it as a compile-time constant. That is, where the final variable is used, it is equivalent to the constant that is accessed directly, and does not need to be determined at run time. This is a bit like a macro substitution in C language. So in the preceding section of code, because the variable B is final decorated, it is treated as a compiler constant, so where B is used, the variable b is replaced directly with its value. The access to variable D needs to be linked at run time. Presumably the difference should be understood, but note that the compiler does this only if the final variable value is known exactly during compilation, as the following code does not optimize:
Public class Test { publicstaticvoid main (string[] args) { = "Hello2" ; Final String B = Gethello (); = B + 2; = = c)) ; } Public Static String Gethello () { return "Hello"; }}
The output of this code is false.
The difference between the Java base-final variable and the normal variable