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
Joined: Jul 27, 2001
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 ]
Joined: Jun 24, 2001
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