是否使用+串联创建的字符串存储在字符串池中? [英] Are strings created with + concatenation stored in the string pool?

查看:68
本文介绍了是否使用+串联创建的字符串存储在字符串池中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如

 String s = "Hello" + " World";

我知道池中有两个字符串Hello和World但是,确实: Hello World进入字符串池?

I know there are two strings in the pool "Hello" and "World" but, does: "Hello World" go into the string pool?

如果是这样,那该怎么办?

If so, what about?

String s2 = new String("Hola") + new String(" Mundo");

每种情况下池中有多少个字符串?

How many strings are there in the pool in each case?

推荐答案

是的,如果通过连接两个 String String $ c> 文字它也将被实习。

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

来自JLS:


因此,测试程序包含
编译单元(§7.3):

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") + " "); // 1
        System.out.print((Other.hello == hello) + " "); // 2
        System.out.print((other.Other.hello == hello) + " "); // 3
        System.out.print((hello == ("Hel"+"lo")) + " "); // 4
        System.out.print((hello == ("Hel"+lo)) + " "); // 5
        System.out.println(hello == ("Hel"+lo).intern()); // 6
    }
}
class Other { static String hello = "Hello"; }
and the compilation unit:
package other;
public class Other { static String hello = "Hello"; }

产生输出:

true  //-> 1
true  //-> 2
true  //-> 3
true  //-> 4
false //-> 5
true  //-> 6

重要的行是4和5. 4代表你在第一种情况下的要求;图5显示了如果一个不是文字(或更一般地,编译时常量)会发生什么。

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).

这篇关于是否使用+串联创建的字符串存储在字符串池中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆