• 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

.equals()

 
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Ranch Hand
Posts: 1365
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 25
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
CAUTION! Do not touch the blades on your neck propeller while they are active. Tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic