aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Strings Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Strings" Watch "Strings" New topic
Author

Strings

santhoshkumar samala
Ranch Hand

Joined: Nov 12, 2003
Posts: 156

snippet 1


Will give NotEqual

snippet2


will give Equal


somebody please explain the logic behind this

and

snippet 3



will give Equal


santhosh<br />SCJP,SCWCD
Bala Muthukumarasamy
Greenhorn

Joined: Oct 24, 2005
Posts: 2
It is always better to use equals method than '==' for string comparison.

The equals() method checks whether two strings have the same characters, whereas the == operator checks if two operands refer to the same String object. '== ' tests to see if the references in the variables point to the same memory address.

Hope this helps...

Thanks
Bala
Jayanth Mathavan
Greenhorn

Joined: Nov 10, 2005
Posts: 16
Hi...

== operator will give false when the two comparing operands are of different objects. so == will return true when the operands refer to the same object.

in the first sinppet " String ".trim() will create a new string object and when that is compared to the second operand "String" it will return false.

in the second snippet "String".trim() operation will not create a new string object since the "String" object is already trimmed so the old object is retained. and when that is compared with "String" it returns true. the same thing applies to snippet three also.

hope i have cleared your doubt.

Bye,
Jayanth.
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

See Corey McGlone's article, Strings, Literally. This should answer a lot of your questions.
[ December 20, 2005: Message edited by: marc weber ]

"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
Ravisekhar Kovuru
Greenhorn

Joined: Sep 23, 2003
Posts: 25
Snippet 1:
In this case the trim() method will create new String object.
This new object is equal to "String" according to equals() method.
But this is not equals to "String" according to ==, because both are entirely different objects.

Snippet 2:
Here, there are actually no spaces to trim in "String".
So, if you see the source code for trim() method you will see that it will return this object when there are no spaces to trim.
That's why they both are equal according to ==

Snippet 3:
Same case here too. The toString() in String class always returns this object.
[ December 20, 2005: Message edited by: Ravisekhar Kovuru ]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Strings