aspose file tools
The moose likes Java in General and the fly likes Constant String comparison with equals Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "Constant String comparison with equals" Watch "Constant String comparison with equals" New topic
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
    
    1

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
    
    2

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
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: Constant String comparison with equals
 
Similar Threads
Finding an element in a map
Need a method for recognizing a pallindrome
why not overload equals ?
"foo".equals(foo) vs foo.equals("foo")
Decorator Pattern.