java String的==和equals

本文详细解析了Java中字符串常量池的工作原理,包括如何使用String.intern()方法,以及在不同JDK版本下(如JDK1.6和JDK1.8)的处理差异。通过具体示例,阐述了字符串对象在堆内存中的创建过程,以及常量池中字符串引用的返回机制。

xxx.intern()检查常量池是否存在xxx代表的字符串,如果存在,直接返回常量池中字符串对象的引用;如果不存在,把xxx的引用复制到常量池,然后返回xxx的引用。

String str1 = new String("Hello")+ new String("World");
System.out.println(str1.intern() == str1);
System.out.println(str1 == "HelloWorld");


结果:
true
true

str1在堆上创建三个对象,分别存放:“Hello”、“World”、“HelloWorld”

str1.intern()发现常量池不存在"HelloWorld",将str1应用放到常量池,因此,str1.intern() == str1 == "HelloWorld"。

String str2 = "HelloWorld";
String str1 = new String("Hello")+ new String("World");
System.out.println(str1.intern() == str1);
System.out.println(str1 == "HelloWorld");


结果:
false
false

str1.intern()发现常量池存在"HelloWorld",返回应用其实是str2,因此,str1.intern() == str2 == "HelloWorld"。

网上说,JDK1.6和JDK1.8处理不一样。不过,对于字符串判断内容是否相等,还是记得用equals来吧。不要将c++ string的==带到Java中来。

System.out.println(str1.intern().equals(str1));
System.out.println(str1.equals("HelloWorld"));

结果:
true
true

转载于:https://my.oschina.net/smallfan/blog/2245492

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值