File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Strings" Watch "Strings" New topic


santhoshkumar samala
Ranch Hand

Joined: Nov 12, 2003
Posts: 156

snippet 1

Will give NotEqual


will give Equal

somebody please explain the logic behind this


snippet 3

will give Equal

santhosh<br />SCJP,SCWCD
Bala Muthukumarasamy

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...

Jayanth Mathavan

Joined: Nov 10, 2005
Posts: 16

== 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.

marc weber

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
Ravisekhar Kovuru

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:
subject: Strings
jQuery in Action, 3rd edition