Win a copy of Rust Web Development this week in the Other Languages 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:
  • Tim Cooke
  • Campbell Ritchie
  • Ron McLeod
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Junilu Lacar
  • Rob Spoor
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Tim Moores
  • Jesse Silverman
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Frits Walraven

.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
 
You showed up just in time for the waffles! And this tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
reply
    Bookmark Topic Watch Topic
  • New Topic