为什么这些陈述会给出不同的答案?
String s1="hello world";
String s2="hello world";
System.out.println(s1.equals(s2));//true
System.out.println(s1 == s2);//true
第二案;
String s1=new String("hello world");
String s2=new String("hello world");
System.out.println(s1.equals(s2));//true
System.out.println(s1 == s2);//false
答案 0 :(得分:1)
s1.equals(s2)
比较两个字符串的内容,而s1 == s2
比较对象'引用。
由于s1和s2都是String类的两个不同实例,因此它们的引用不相等。 ==
运算符对所有对象都采用这种方式。
答案 1 :(得分:0)
==
只比较两个引用 - 即它测试两个操作数是否引用同一个对象。 s1
和s2
是两个不同的对象,因此比较为false
。