not so smart guy still curious to learn new stuff every now and then
42
SCJP 1.4 * SCWCD 1.4 * SCBCD 1.3 * SCJA 1.0 * TOGAF 8
If it's exactly like you've written, the compiler should optimize it away. Let the string _not_ be an compiletime constant, the two aporroaches differ in that the fist has to allocate a temporary object, therefore I would prefer the second. Also, it read's better for me.
The only real implication (other than style of coding) is that if foo == null, the 2nd approach (foo.equals("foo")) would throw a NullPointerException, whereas the first approach ("foo".equals(foo)) would simply return false.
and therefore "foo".equals(foo) is both safer and more semantically correct (as null is by definition not equal to anything, even itself).
Tony Morris
Java Q&A (FAQ, Trivia)
Associate Instructor - Hofstra University
Amazon Top 750 reviewer - Blog - Unresolved References - Book Review Blog
No one is violating any contract by using "foo".equals(foo). This is programmatically safer in that if foo is null you get false and not a NullPointerException.
Tony Morris
Java Q&A (FAQ, Trivia)
Sun Certified Programmer for the Java 2 Platform
Did you see how Paul cut 87% off of his electric heat bill with 82 watts of micro heaters? |