Java中的字符串:equals vs == [英] Strings in Java : equals vs ==
本文介绍了Java中的字符串:equals vs ==的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能重复:
如何比较Java中的字符串?
String s1 = "andrei";
String s2 = "andrei";
String s3 = s2.toString();
System.out.println((s1==s2) + " " + (s2==s3));
给出以下代码为什么第二个比较s2 == s3为真?
什么是s2.toString()返回?实际位于哪里(s2.toString())
?
Giving the following code why is the second comparison s2 == s3 true ?
What is actually s2.toString() returning ? Where is actually located (s2.toString())
?
推荐答案
首先 String.toString
是一个无操作:
/**
* This object (which is already a string!) is itself returned.
*
* @return the string itself.
*/
public String toString() {
return this;
}
其次,字符串常量被实现,因此s1和s2在幕后更改为相同的String实例。
Second of all, String constants are interned so s1 and s2 are behind the scenes changed to be the same String instance.
这篇关于Java中的字符串:equals vs ==的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文