• 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

String Compare

 
Ranch Hand
Posts: 177
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Could somebody explain why the result from case 1 is different from case 2.
case1 : if("String".toString() == "String")
case2 : if(" String ".trim() == "String")
Thanks in Advance
 
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
case 1: Here "String" is returned as it is.
API for toString() says "This object (which is already a string!) is itself returned."
case 2:Here the white space from both the ends of the String is removed and a new String object is returned.
Rashmi
 
Ranch Hand
Posts: 3244
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The results should be true then false.
The first returns true because using the toString method on a String simply returns the String itself. The compiler knows this and can just use the same string literal from the string pool for both of the Strings in the method.
The trim method returns a new String that has had any leading and trailing whitespace removed. If there were no spaces it would return the same string (take out the spaces and run it and your output will be true, true). In the example you posted becasue there are spaces it returns a new String object. Because == compares the objects to see if they are the same the result is false.
If you use the same String (with spaces but change == to equals then you'll get true, true. Because equals is overridden for Strings to compare the actual contents.

hope that helps
Dave
 
Harsha Jay
Ranch Hand
Posts: 177
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Rashmi and Dave for quick response.
This forum is definitely a great place to learn quickly.
Keep up the good job !!!
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic