java string的内存模型_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"

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值