• 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

Constant String comparison with equals

 
Ranch Hand
Posts: 119
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
They both work, but which is better

boolean isFoo1(String s){
return s.equals("Foo");
}

boolean isFoo2(String s){
return "Foo".equals(s); // I think it is faster
}

Your comments?
 
Saloon Keeper
Posts: 15484
363
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Personally I prefer the first option, because it more or less follows the concept of variable -> operator -> constant.

The second option has the 'benefit' that if s is null, it will return false, instead of throwing a NullPointerException.
I actually like that it throws a NullPointerException, because it indicates that something in my program might have gone wrong. Others disagree though.
 
Rancher
Posts: 4803
7
Mac OS X VI Editor Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
As a rule, I much prefer clear, obvious code. Thus, I prefer

if (s.equals("Foo"))

just because its obvious in a nanosecond what its doing. We write our software as much for the ease of future readers/engineers as we do for the ease of compilation and execution.
 
Sheriff
Posts: 22781
131
Eclipse IDE Spring VI Editor Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
For me it depends. If the variable shouldn't be null I use s.equals("Foo"). Otherwise, being lazy, I prefer "Foo".equals(s) over s != null && s.equals("Foo").
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic