• 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:
  • Tim Cooke
  • Campbell Ritchie
  • Ron McLeod
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Junilu Lacar
  • Rob Spoor
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Tim Moores
  • Jesse Silverman
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Frits Walraven

String comparison

 
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
public class abc {
public static void main(String args[]) {
String str1 = "string1";
String str2 = "string1";
System.out.println(str1==s.str);
System.out.println(str1.equals(str2));
System.out.println(str1=="string1");
}
}

I tried the above comparisons and got the result as 'true' in all the three cases. but if i initialize str1 and str2 as :
String str1 = new String("string1");
String str2 = new String("string1");
This comparison returns false.
plez explain the reason for the same...i will be greatful....
Monika

 
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Monika Pasricha:
public class abc {
public static void main(String args[]) {
String str1 = "string1";
String str2 = "string1";
System.out.println(str1==s.str);
System.out.println(str1.equals(str2));
System.out.println(str1=="string1");
}
}
when you say that
String str1 = "string1";
internally an anonymous string object is created and every time
"string" is equated to some String object ( like in this case str1, str2,.... ) the reference to the same anonymous String object is returned . This means that str1 and str2 will have the same reference value.
yr first println statement should be corrected as
System.out.println(str1==str2); //returns true becoz of same reference
System.out.println(str1.equals(str2)); // this mearly compares // //the contents of the two string objects since in this case both //store "string" it returns true
System.out.println(str1=="string1"); // this is same as case 1 //above where an anonymous object is created internally. Ans is //true.
String str1 = new String("string1");
String str2 = new String("string1");
In the above cases we are forcibly creating two new string objects and hence two new references . there for all the tests except
System.out.println(str1.equals(str2));
should retrun false.
HTH
Sasidhar


 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic