String知识
参考链接:
- String的内存模型,为什么String被设计成不可变的: https://juejin.im/post/6844903497708601351
- ScjpTipLine-StringsLiterally: https://javaranch.com/journal/200409/ScjpTipLine-StringsLiterally.html
- 关于创建String对象过程的内存分配: https://blog.csdn.net/xiabing082/article/details/49759071
| String.intern():常量池存在,返回常量池中的那个对象;常量池不存在,则放入常量池,并返回本身
只有编译期暴露的字面量才会放到常量池中。程序运行时,除非手动向常量池中添加常量(比如调用intern方法),否则jvm不会自动添加常量到常量池。
JDK1.8中常量池存储的是String对象不是引用。 - https://blog.csdn.net/weixin_39460458/article/details/79982765
//等号赋值,注意字面量的存在
String str ="hello"; //一个实例
str.intern() == str; // --> true hello 存在于常量池中,返回常量池中的hello对象内存地址等同于str变量所指向的hello对象内存地址。
// "hello"本身就是一个字符串,并放入常量池,故intern()返回常量池中的对象
String str2 = new String("hello"); //两个实例
str2.intern() == str2;// --> false 暴露的字面量hello存在于常量池中,返回常量池中的对象内存地址不等同于hello的堆地址。
//没有任何字面量为"RyanMiao"暴露给编译器,所以常量池没有创建"RyanMiao",所以,intern返回this
String s3 = new StringBuilder("Ryan").append("Miao").toString();
s3.intern() == s3; //--> true
疑问:
String strA = “a”;
String strBC = “bc”;
String strABC = strA+strBC;
常量池应该有a 和 bc 但没有 abc
abc为什么没有放到常量池中,因为abc没有暴露给编译器。