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

posted on   乐之者v  阅读(562)  评论(0编辑  收藏  举报

编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示