• 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
  • Tim Cooke
  • paul wheaton
  • Jeanne Boyarsky
  • Ron McLeod
Sheriffs:
  • Paul Clapham
  • Liutauras Vilda
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
Bartenders:

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.
 
Do the next thing next. That’s a pretty good rule. Read the tiny ad, that’s a pretty good rule, too.
Smokeless wood heat with a rocket mass heater
https://woodheat.net
reply
    Bookmark Topic Watch Topic
  • New Topic