Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

one more abhilash mock question

 
Don Bosco
Ranch Hand
Posts: 108
  • Mark post as helpful
  • send pies
  • 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.
 
Dinesh Kumar
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • 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
 
Ron Newman
Ranch Hand
Posts: 1056
  • Mark post as helpful
  • send pies
  • 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.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic