-4

why do these statements give different answers?

String s1="hello world";
String s2="hello world";
 System.out.println(s1.equals(s2));//true
    System.out.println(s1 == s2);//true

2nd case;

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
mad max
  • 61
  • 9

2 Answers2

1

s1.equals(s2) compares the content of the two strings whereas s1 == s2 compares the objects' references.

Since both s1 and s2 are two different instances of the String class, their references are not equal. The == operator behaves this way for all Objects.

zlandorf
  • 1,100
  • 11
  • 15
0

== just compares two references - i.e. it tests whether the two operands refer to the same object. s1 and s2 are two different objects so that's why the comparison is false.

Bahramdun Adil
  • 5,907
  • 7
  • 35
  • 68
NiallMitch14
  • 1,198
  • 1
  • 12
  • 28