Java String内存模型
String内存模型 示例:
public static void strMemoryCompare() {
String s1 = "HelloWorld";
String s2 = new String("HelloWorld");
String s3 = "Hello";
String s4 = "World";
String s5 = "Hello" + "World";
String s6 = s3 + s4;
System.out.println(s1 == s2);
System.out.println(s1 == s5);
System.out.println(s1 == s6);
System.out.println(s1 == s6.intern());
System.out.println(s2 == s2.intern());
}
解答如下:
public static void strMemoryCompare() {
//s1是变量,存放在栈里。"HelloWorld"存放在常量池中
String s1 = "HelloWorld";
//new String("HelloWorld")是个对象,存放在堆。
String s2 = new String("HelloWorld");
String s3 = "Hello";
String s4 = "World";
// "Hello" + "World" 在编译时会被优化成"HelloWorld"
String s5 = "Hello" + "World";
// 通过加号拼接两个字符串,会在堆上创建的新的对象
String s6 = s3 + s4;
System.out.println(s1 == s2); //false,s1指向常量池中的"HelloWorld",s2指向对象String("HelloWorld")
System.out.println(s1 == s5); //true,都指向常量池的"HelloWorld"
System.out.println(s1 == s6); //false,因为s3+s4相当于创建了新对象.
// intern()方法会监测常量池中是否有该字符串的值的字面量,有就返回字符串常量的地址,没有则新建新建字符串常量并返回内存地址。
System.out.println(s1 == s6.intern()); //true,都指向常量池中的"HelloWorld"
System.out.println(s2 == s2.intern()); //false,s2指向对象,s2.intern()指向常量池"HelloWorld"
}
参考资料:
https://www.cnblogs.com/aiqiqi/p/10770864.html#_label4
https://blog.csdn.net/fenglllle/article/details/81479179
https://juejin.im/post/5e9903dfe51d454714427e56
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了