两种情况有什么区别;在java字符串?

时间:2016-02-18 10:05:06

标签: java string

为什么这些陈述会给出不同的答案?

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

2 个答案:

答案 0 :(得分:1)

s1.equals(s2)比较两个字符串的内容,而s1 == s2比较对象'引用。

由于s1和s2都是String类的两个不同实例,因此它们的引用不相等。 ==运算符对所有对象都采用这种方式。

答案 1 :(得分:0)

==只比较两个引用 - 即它测试两个操作数是否引用同一个对象。 s1s2是两个不同的对象,因此比较为false