Are strings created with + concatenation stored in the string pool?

前端 未结 6 732
盖世英雄少女心
盖世英雄少女心 2020-12-09 06:16

For instance

 String s = \"Hello\" + \" World\";

I know there are two strings in the pool \"Hello\" and \"World\" but, does: \"Hello World\

6条回答
  •  难免孤独
    2020-12-09 06:38

    Yes, if a String is formed by concatenating two String literals it will also be interned.

    From the JLS:

    Thus, the test program consisting of the compilation unit (§7.3):

    package testPackage;
    class Test {
        public static void main(String[] args) {
            String hello = "Hello", lo = "lo";
            System.out.print((hello == "Hello") + " ");
            System.out.print((Other.hello == hello) + " ");
            System.out.print((other.Other.hello == hello) + " ");
            System.out.print((hello == ("Hel"+"lo")) + " ");
            System.out.print((hello == ("Hel"+lo)) + " ");
            System.out.println(hello == ("Hel"+lo).intern());
        }
    }
    class Other { static String hello = "Hello"; }
    and the compilation unit:
    package other;
    public class Other { static String hello = "Hello"; }
    

    produces the output:

    true
    true
    true
    true
    false
    true
    

    The important lines are 4 and 5. 4 represents what you are asking in the first case; 5 shows you what happens if one is not a literal (or more generally, a compile-time constant).

提交回复
热议问题