• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

string doubt second one

 
Karu Raj
Ranch Hand
Posts: 481
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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); //XYZ
System.out.println(s3==s4);

Why is the out put at XYZ is false ?though both reference to same "arit"
 
Sandeep Chhabra
Ranch Hand
Posts: 340
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Originally posted by Karthik Rajashekaran:
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); //XYZ
System.out.println(s3==s4);

Why is the out put at XYZ is false ?though both reference to same "arit"


I think both s2 and s3 do not refer to same object.
s2 refers to a String Object in pool, whereas s3 refers to a new object created by the statement earlier:
String s2 = s1.replace('m','r');
replace method always returns a new String Object even if that string is already present in the pool.

Correct me if I am wrong.

Sandy
 
Karu Raj
Ranch Hand
Posts: 481
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yes you are right

again i made silly mistake
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic