How Java String pool works when String concatenation?

北战南征 提交于 2019-11-30 16:34:20

"When the string is created by concatenation does java make something different or simple == comparator have another behaviour?"

No it does not change its behavior, what happens is that:

When concatenating two string literals "a" + "b" the jvm joins the two values and then check the string pool, then it realizes the value already exists in the pool so it just simply assign this reference to the String. now in more details:

Look at the compiled bytecode below of this simple program:

public class Test  {    
    public static void main(String... args) {
        String a = "hello world!";
        String b = "hello" + " world!";
        boolean compare = (a == b);
    }
}

First the JVM loads the string "hello world! and then push it to string pool (in this case) and then loads it to the stack (ldc = Load constant) [see point 1 in Image]

Then it assign the reference created in the pool to the local variable (astore_1) [see point 2 in Image]

Notice that the reference created in the string pool for this literal is #2 [See point 3 in Image]

The next operation is about the same: in concatenates the string, push it to the runtime constant pool (string pool in this case), but then it realizes a literal with the same content already exists so it uses this reference (#2) and assign in to a local variable (astore_2).

Thus when you do (a == b) is true because both of them are referencing to the string pool #2 which is "hello world!".

Your example C is kind of different tho, because you're using the += operator which when compiled to bytecode it uses StringBuilder to concatenate the strings, so this creates a new instance of StringBuilder Object thus pointing to a different reference. (string pool vs Object)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!