The value of the final control variable

String a="A"; String b="B"; final String c="C"; final String d="D"; String e=a+b; String f=a+b; System.out.println(e==f);//false String g=c+d; String h=c+d; System.out.println(g==h);//true 

Why is this so? String objects created in special memory are called a string constant pool. But here is the meaning of the final variable.

+4
source share
4 answers

The compiler sees that c and d are final. This means that the compiler knows that c and d will never change. So it compiles the code

 String g = "CD"; String h = "CD"; 

g and h, therefore, are two references to the same literal STring that is interned.

He cannot optimize e and f in the same way, because a and b are not final and can change.

+1
source

The final keyword does not allow you to reassign this variable to another instance of String. Thus, although String itself is immutable, a variable that refers to it can be changed if it is not explicitly marked final.

Now I am less defined regarding the exact semantics of what you experience here. But in general, since the variable is final, c+d can now be considered as a compiler constant (it can never have a value other than "CD" . "CD" The value is calculated at compile time and can itself be considered as a constant that is placed in the interned string pool .

+4
source

final means that you cannot change the value of this line later in your program. Also:

If the final variable contains a reference to the object, then the state of the object can be changed by operations on the object, but the variable will always refer to the same object. ( source )

+1
source

The Java compiler sees that you have specified your variables as final (making them constants, not variables), computes c+d at compile time, and assimilates the result.

+1
source

Source: https://habr.com/ru/post/1394023/


All Articles