• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

question on Strings

 
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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);


Above program segment produces following output:
arit
amit
false
true

i thought it will be:
arit
amit
true
true

I thought that Strings 's2' and 's3' will be pointing to the same String literal "arit" in String constant pool. But its giving the output as false when s2 and s3 are compared with == operator. can anybody explain why?
 
Marshal
Posts: 79180
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Can the compiler work out whether the two Strings are the same? Go through the information required for the compiler to work out that s2 and s3 are identical, then you will see why it produces false.
 
Sheriff
Posts: 22783
131
Eclipse IDE Spring VI Editor Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The methods in String that return another String reference usually create a completely new String object, and return a reference to this.

When using Strings, always use equals over == unless you've called intern() yourself:
 
reply
    Bookmark Topic Watch Topic
  • New Topic