aspose file tools
The moose likes Java in General and the fly likes .equals() Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Java in General
Reply Bookmark ".equals()" Watch ".equals()" New topic
Author

.equals()

Devavrat Bagayat
Greenhorn

Joined: Jun 24, 2001
Posts: 25
Which of the following methods for String comparison would be appropriate and why ?
String s = "abc";
1.) s.equals("abc");
2.) "abc".equals(s);
Thanks
David Weitzman
Ranch Hand

Joined: Jul 27, 2001
Posts: 1365
Both!
The equals contract (UBB won't let me put parenthesis in a URL, so you'll have to browse there yourself) requires, among other things, that:

It is symmetric: for any reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.

Thus the two forms work equally well.
If s were null, however, the first form would throw a NullPointerException while the second would return false. That, plus the fact that the string constant is really the most important part of the expression, lead some people to prefer the second form.
[ May 10, 2003: Message edited by: David Weitzman ]
Devavrat Bagayat
Greenhorn

Joined: Jun 24, 2001
Posts: 25
Hey David,
Thanks for your instant reply.
When a friend of mine asked this same question, I had thought about the same regarding the use of 2 option when the value of s is null, but was not sure, so wanted to have a confirmation and getting an instant confirmation has indeed helped me.
Thanks again
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: .equals()
 
Similar Threads
Doubt in String's
string construction
why we r not using 'new' for String declaration
strings
== and equals in String Class