• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

replace

 
Ahmad Mudassir
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi every one !
What is the output (Assuming written inside main)
String s1 = new String("amit");
System.out.println(s1.replace('m','r'));
System.out.println(s1);
String s3="arit";
String s4="arit";
String s2 = s1.replace('m','r');
System.out.println(s2==s3);
System.out.println(s3==s4);
correct is
arit
amit
false
true
but i think it s2 also equal to s3
could any one clear this.
 
Craig Demyanovich
Ranch Hand
Posts: 173
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The == operator when used with object references is shallow by default, which means that it returns true only if the references point to the same object. The equals() method, when properly overridden for the type in question, usually works on the "contents" of the object. So, s2.equals(s3) would return true, while (s2 == s3) returns false because s2 and s3 don't refer to the same object.
Read up on constructing String objects with literals versus with the new operator, if you haven't already. There are many nuances with the String class.
Craig
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic