final String

Let's observe the following code why their values ​​are "ab" but why their results are not the same?

		String a="a";
        final String b = "b";
        String ab1 = "ab";
        String ab2 = a + b;
        String ab3 = a + "b";
        String ab4 = "a" + b;
        String ab5 = "a" + "b";
        System.out.println(ab1 == ab2); //false
        System.out.println(ab1 == ab3); //false
        System.out.println(ab2 == ab3); //false
        System.out.println(ab1 == ab4); //true
        System.out.println(ab2 == ab4); //false
        System.out.println(ab3 == ab4); //false
        System.out.println(ab1 == ab5); //true
首先我们大家要知道“==”和“equals”是不同的。
“==”比较的是两个对象的地址是否相同,但“equals”比较的是两个对象的值是否相同。

When learning String, we all know that there is a final in String, which means that variables of type String cannot be changed after they are defined, but some people may ask.

		String a="a";
        a="b";
        System.out.println(a);//b

In this code, the value of a has changed from the original "a" to "b". Isn't this a change? How can it be said that it has not changed.
In fact, there is really no value of "a" in the memory, but at the beginning, a pointed the pointer to a place where the address of "a" was stored, and then changed the pointer to a place where "b" was stored. But the "a" piece of memory has not disappeared, but there is no variable guide.

So the question is, since there is already final in the source code of String, what does it mean to add a final before String?
Adding a final before String fixes its guidelines so that it doesn't point to another address. When final is added, this value actually exists in the constant pool. When this variable is called, the program will treat it as a constant. Now this also means that String ab4 = "a" + b is actually String ab4 = "a" + "b", which should be defined first in the constant pool is ab1, so ab4 and ab5 are both common when they are defined Point to ab1, then why don't the other values ​​point to the address of ab1? It is because when the Java program is running, in order to ensure that it can be compiled completely, the values ​​that cannot be parsed into variables that already exist in the constant pool are re-opened for them and stored in them, because the variable b is prefixed with If fianl is added, it is regarded as a constant when it is called, and fianl is not added before the variable a, so it is not regarded as a constant when called.
If you don't believe me, you can print out their addresses and take a look. Below is the code to print the addresses.

System.out.println(System.identityHashCode(ab1));

Guess you like

Origin blog.csdn.net/MCYZSF/article/details/89890555