| Author |
Constant String comparison with equals
|
Tejas Jain
Ranch Hand
Joined: Mar 04, 2008
Posts: 114
|
|
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?
|
"Knowing is not enough, you must apply... Willing is not enough, you must do."
--Bruce Lee
|
 |
Stephan van Hulst
Bartender
Joined: Sep 20, 2010
Posts: 3056
|
|
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
Joined: Aug 11, 2007
Posts: 4422
|
|
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
Joined: Oct 27, 2005
Posts: 19216
|
|
|
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").
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
 |
|
|
subject: Constant String comparison with equals
|
|
|