Win a copy of Escape Velocity: Better Metrics for Agile Teams this week in the Agile and Other Processes forum!
  • 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
  • Liutauras Vilda
  • Tim Cooke
  • Paul Clapham
  • Jeanne Boyarsky
Sheriffs:
  • Ron McLeod
  • Frank Carver
  • Junilu Lacar
Saloon Keepers:
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Al Hobbs
  • Carey Brown
Bartenders:
  • Piet Souris
  • Frits Walraven
  • fred rosenberger

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 ]
 
Morning came much too soon and it brought along a friend named Margarita Hangover, and a tiny ad.
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic