• 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

"foo".equals(foo) vs foo.equals("foo")

 
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I was asked this question and was unsure of the correct answer,
what would be the implications between these 2 approaches for comparing strings.
String foo = "foo";
so the 2 different ways would be
boolean same = "foo".equals(foo);
vs
boolean same = foo.equals("foo");
I have my guesses, but wanted to see what you guys have to say.
thanks
Jesse
 
Ranch Hand
Posts: 348
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
my 2c,
String foo = "foo";
foo is
1. String object reference, Stirng foo -> from left-side
2. String literal content, "foo" - > from right-side
follow the logic
boolean same = "foo".equals(foo); -> right-side.equals(left-side)
boolean same = foo.equals("foo"); -> left-side.equals(right-side)
both return true
[ April 06, 2004: Message edited by: chi Lin ]
 
Ranch Hand
Posts: 55
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Ranch Hand
Posts: 202
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
[ April 06, 2004: Message edited by: Billybob Marshall ]
 
Ranch Hand
Posts: 5093
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
and therefore "foo".equals(foo) is both safer and more semantically correct (as null is by definition not equal to anything, even itself).
 
Ranch Hand
Posts: 1923
Scala Postgres Database Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
and therefore it's safer?
If you don't know, whether foo is null, you don't know it afterwards.
It may hide a problem till the day before the big breakdown
And semantically:
You don't ask:

but whether a variable is "foo".
In natural language you ask: 'Is his name "foo"?' rather than 'is "foo" his name?'
 
Ranch Hand
Posts: 884
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Just to add on, if you simply use the equals() method in comparing strings, its case sensitive, meaning "foo" & "Foo" are different.
Use equalsIgnoreCase() method instead if you need to compare strings, case-insensitive.
 
Ranch Hand
Posts: 1608
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


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.


This doesn't seem to make any sense (at least, not to me).
OK, "Let the string _not_ be an compiletime constant" (assuming you are referring to the only compile-time constant)

How does this make the second statement more preferable ?
They are syntactically equivalent.


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.


How so ? Does this imply that you write code in a "safe way" ? That is, you don't dereference a reference if possible in the off-chance that it may be referring to null ? That is extremely dangerous. One should ("should" being used loosely here) design and implement in such a way that this can be "guaranteed" rather to being "safe". Unit tests can also assist in making this "guarantee" (quoted to demonstrate a lack of ignorance of real world scenarios).


and therefore "foo".equals(foo) is both safer and more semantically correct (as null is by definition not equal to anything, even itself).


The equality test contract demands that a test for null returns false. If you violate this contract, you have "bigger worries on your hands" than the order of String comparison, or even a java.lang.NullPointerException, since this is often easier to diagnose than a violation of the java.lang.Object method contracts.
<my-two-cents-worth>
It doesn't make a difference.
If it happened to make a performance difference on some VM implementations (which I'm neither proposing nor discounting as a possibility - I'm simply not going to bother trying it), it would be implementation dependant behaviour anyway, so why bother worrying ?
The maximum possible benefit could be readability, and even then, that is subjective. You read your own code more than anyone else does right ? So simply do it "your way".
</my-two-cents-worth>
 
mister krabs
Posts: 13974
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The equality test contract demands that a test for null returns false. If you violate this contract, you have "bigger worries on your hands" than the order of String comparison, or even a java.lang.NullPointerException, since this is often easier to diagnose than a violation of the java.lang.Object method contracts.
I'm not sure what you mean here, exactly. 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. If your requirement is that if the String foo contains the value "foo" then do a bunch of things, then in order to correctly check for equality you would need to do one of these things:
if (foo != null && foo.equals("foo"))
or
if ("foo".equals(foo))
The second option is cleaner, don't you think?
The whole issue of unit testing has nothing to do with this. If foo could be allowed to be null then all unit testing will do is push your code into the first option when you do your testing. Why not just use the second to start?
 
Tony Morris
Ranch Hand
Posts: 1608
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I agree with most of your post, I think you have misunderstood my points made. What I cannot agree with, however, is this (extremely dangerous) statement:


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.


Agreed, nobody is violating any contract here (I believe this is a misunderstanding of what I was saying),
<b><blink><flash-lights><achtung>HOWEVER</achtung></flash-lights></blink></b>
To defenisively program such that you avoid a NullPointerException and the application quietly consumes the null value by returning false is extremely dangerous. This is distinct from predicting the possibility that the reference may be null and that if it is, you want that same desired result (returning false). You next statement suggests that this is what you meant, but I must ensure that this distinction is in place.
 
Ranch Hand
Posts: 171
1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Jeroen Wenting wrote: "and therefore "foo".equals(foo) is both safer and more semantically correct (as null is by definition not equal to anything, even itself). "
This is wrong. Null is equal to itself. The following prints true:
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic