When does the pool change?

后端 未结 3 1262
闹比i
闹比i 2020-11-30 13:43

I have two questions:

public static void main(String[] args) {
  String s1 = \"bla\";
  String s2 = \"b\" +\"l\" + \"a\";
  String s3 = \"b\".concat(\"l\").c         


        
3条回答
  •  执笔经年
    2020-11-30 14:04

    Why does s1 and s2 point to the same object, whereas s1 and s3 doesn't? (There is no usage of new keyword).

    Since String in Java are Immutable, so any method of string class will return a new String object (there are some exception though - one is substring method). Hence concat method creates a new string, that goes to the Heap, and is not added to constant pool.

    As far as the case of s1 and s2 is concerned, both strings are known at compile time, and hence they are same string literals.

    Note that the concatenation operation in 2nd string: -

    String s2 = "b" +"l" + "a";
    

    is evaluated at compile time, and the result is known to be same as the first string, and one entry is made to the constant pool.

提交回复
热议问题