• Post Reply Bookmark Topic Watch Topic
  • New Topic

Constant String comparison with equals  RSS feed

 
Tejas Jain
Ranch Hand
Posts: 119
  • Mark post as helpful
  • send pies
  • 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?
 
Stephan van Hulst
Saloon Keeper
Posts: 7987
143
  • Mark post as helpful
  • send pies
  • 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.
 
Pat Farrell
Rancher
Posts: 4686
7
Linux Mac OS X VI Editor
  • Mark post as helpful
  • send pies
  • 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.
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • 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").
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!