• 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

one more abhilash mock question

 
Ranch Hand
Posts: 108
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
if("String".trim() == "String".trim())
System.out.println("Equal");
else
System.out.println("Not Equal");

output is Equal.
Can anybody explain me what is happening behind the scenes.
 
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
According to Java API for the trim method,
"if there is no character with a code greater than '\u0020' in the string, then a new String object representing an empty string is created and returned."
So in this case it is just returning an empty string. Since, java optimises String usage by putting them on a common shared pool wherever possible, there is actually only one empty String object created and both point to the same object. That is why the comparison returns Equal.
Hope it helps.
Dinesh
SCJP 1.4
 
Ranch Hand
Posts: 1056
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
But all the characters in "String" have codes larger than \u0020.
Since "String" neither begins nor ends with a whitespace character, String.trim("String") returns its argument.
reply
    Bookmark Topic Watch Topic
  • New Topic