String s1=new String("Duke");
String s2=new String("Duke");
You are clearly instantiating TWO new String objects. I can tell because I see the
word "new" written twice!!
Each new String object gets assigned to a different reference variable, s1 and s2. So clearly, these are two different objects, won't you agree?
If they are two different objects, they can NEVER be equivalent (ie, the same) so the expression s1==s2 will always be false.
It's like, my name is Rob. And I have a friend named Rob. But we are not the same person/object, are we?
Now, the equals() method of the String class, by definition, compares the internal character sequences stored in the String object. Since both objects are storing the same character sequences (Duke), the expression s1.equals(s2) is true.
It's like back to my friend and I. My name is Rob. His name is Rob. Are our names the same (equals())??
YES!
[ February 13, 2002: Message edited by: Rob Ross ]