Which String method: "contains" or "indexOf > -1"?

sashank picture sashank · May 23, 2012 · Viewed 45.6k times · Source

Which of the following ways is an efficient way of determining substring containment?

if (str.indexOf("/") > -1)

or

if (str.contains("/")) 

Answer

Alex Lockwood picture Alex Lockwood · May 23, 2012

Take a look at the java.lang.String source code. The contains method is implemented using a call to indexOf, so they are essentially the same.

public boolean contains(CharSequence s) {
    return indexOf(s.toString()) > -1;
}

You should use whichever method makes your code more readable. If you are checking to see if a String contains a specific substring, use contains. If you are looking for the substring's starting index, use indexOf.


Edit:

A couple of answers mention that indexOf should be preferred over contains due to the fact that contains makes an additional method call, and is thus, less efficient. This is wrong. The overhead caused by an additional method call in this case is totally insignificant. Use whichever method makes the most sense in the context of your implementation. This will make your code more readable.