String常量地址变动引起的诡异结果

2020-06-18  

​周末跟一个题友讨论这段代码会创建几个对象。

String s = new String("xyz");

 

答案是我在网上看到的,觉得应该是对的,就录上去了。

两个或一个第一次调用 new String("xyz"); 时,会在堆内存中创建一个字符串对象,同时在字符串常量池中创建一个对象
"xyz"第二次调用 new String("xyz"); 时,只会在堆内存中创建一个字符串对象,指向之前在字符串常量池中创建的 "xyz"

 

然后有题友就在小程序里给我留言,贴了段代码,为了说明问题,我把它做了修改。

String s = new String("2");
s.intern();
String s2 = "2";
System.out.println(s == s2);​

String s3 = new String("1") + new String("1");
s3.intern();String s4 = "11";
System.out.println(s3 == s4);

 

JDK 1.8 的打印值

false
true

 

表面看上去:

第 1 个 false 很好理解,常量和对象地址不相等。

那为啥第 2 个返回的是 true ?而把 s3.intern(); 这行代码去掉,却返回 false,这就很怪异。

 

于是乎,翻了 String intern() 方法的作用

/**
 * Returns a canonical representation for the string object.
 * <p>
 * A pool of strings, initially empty, is maintained privately by the
 * class {@code String}.
 * <p>
 * When the intern method is invoked, if the pool already contains a
 * string equal to this {@code String} object as determined by
 * the {@link #equals(Object)} method, then the string from the pool is
 * returned. Otherwise, this {@code String} object is added to the
 * pool and a reference to this {@code String} object is returned.
 * <p>
 * It follows that for any two strings {@code s} and {@code t},
 * {@code s.intern() == t.intern()} is {@code true}
 * if and only if {@code s.equals(t)} is {@code true}.
 * <p>
 * All literal strings and string-valued constant expressions are
 * interned. String literals are defined in section 3.10.5 of the
 * <cite>The Java&trade; Language Specification</cite>.
 *
 * @return  a string that has the same contents as this string, but is
 *          guaranteed to be from a pool of unique strings.
 */
public native String intern();

 

大致意思就是,如果常量池有 equal 的字符串就返回常量池这个,如果没有就把这个字符串对象添加进常量池,返回这个对象的引用。所有字符串字面量和字符串值常量表达式都是 interned。

 

JDK 1.8 关于这块的说明文档在这里:

https://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-3.10.5

 

先看这段代码内存变化

String s = new String("2");
s.intern();
String s2 = "2";
System.out.println(s == s2);

 

new String("2"); 会同时在常量池和堆中创建两个对象,画个图帮助理解

 

再来看这段代码

String s3 = new String("1") + new String("1");
s3.intern();
​​​​​​​String s4 = "11";
System.out.println(s3 == s4);

 

String s3 = new String("1") + new String("1");

是通过 StringBuilder 实现字符串相加,javap 查看汇编指令

 

执行后的内存示意图如下

s3.intern();
​​​​​​​String s4 = "11";
执行后,按照 API 的描述, s3.intern() 会把 s2 字符串对象添加到常量池返回引用,内存示意图如下

​​​​​​​

看到这里应该知道为什么返回 true 了。

 

网上还有一枚有趣的例子:

String s1 = new StringBuilder("计算机").append("软件").toString();
System.out.println(s1.intern() == s1);​
String s2 = new StringBuilder("Java(TM) SE ").append("Runtime Environment").toString();
System.out.println(s2.intern() == s2);

打印结果

true
false

可以自己研究一下为什么,哈哈!

 

PS:

图中始终强调了 JDK 1.8,因为在 JDK 1.6 及以下跟 1.8 的字符串常量池的存储机制与存储位置是不一样的,所以结果也不一定一致。

 

ConstXiong 备案号:苏ICP备16009629号-3