• 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 operation

 
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi,
following is a piece of code from javabeat mock exam 12.
if("String".trim() == "String".trim())
System.out.println("Equal");
else
System.out.println("Not Equal");
answer is it prints NOt equal.

* if(" String ".trim() == "String")
System.out.println("Equal");
else
System.out.println("Not Equal");
answer is Equal.


* if("String".replace('g','G') == "String".replace('g','G'))
System.out.println("Equal");
else
System.out.println("Not Equal");

answer is Not equal.
I am confused.Please explain.
 
Sheriff
Posts: 11343
Mac Safari Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
First, I think there's a typo: The first example prints "Equal" and the second prints "Not Equal."

The question here is whether the method returns a new String.

Note the API documentation for the trim method, which says it returns "A copy of this string with leading and trailing white space removed, or this string if it has no leading or trailing white space."

In the first case, "String" has no leading or trailing white space, so "String".trim() returns a reference to the original String without creating anything new. Also, because this is a String literal, both occurrences of "String" reference the same object, and therefore "String".trim() == "String".trim() returns true.

In the second case, " String " requires trimming, and so a new String is created. Because this is a new String, it is not referencing the same object as the literal. Therefore, " String ".trim() == "String" returns false.

In the third case, the replace method also returns new Strings, and so the comparison returns false.

(Related topic: Strings Literally.)
[ June 18, 2007: Message edited by: marc weber ]
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic