Java设计者为了提高字符串的性能,设计了字符串常量池。在方法区中。
JDK 1.8 中,已经把字符串常量池从方法区的运行时常量池中分离到堆中了。字符串常量池中存储的就是对象。
参考资料:
JDK1.8版本java字符串常量池里存的是String对象还是引用?
利用一个题目巩固一下:
String name = new String(“A” + ”B”);
创建了几个对象:
- 三个字符串常量:“A”,“B”,“AB”(常量池对象)
- 一个对象 (堆对象)
- 一个引用
tips: 常量池中先看是否有该字符串对象,没有就创建,有就返回对象引用。
附 intern() 方法的 api 文档注释:
* 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>
intern方法参考资料:
jdk1.8中String的intern方法简单介绍