7/16/2010

String.contains and String.indexOf

To check if a string contains a substring, I usually use:

if(s.indexOf(sub) >= 0)
For JDK 5 or later, a contains method can also be used, which seems to be a little more readable:
if(s.contains(sub))
The signature of contains method is:
public boolean contains(java.lang.CharSequence s);
Note that CharSequence is a super-interface of String, StringBuffer, StringBuilder, java.nio.CharBuffer, javax.swing.text.Segment. So you can pass any of the 5 types to contains method.

The current implementation of contains method just convert the param to String and calls indexOf.

3 comments:

Milan Vachhani said...

Only Difference between two is contains return boolean value while indexOf returns int value.

Steve Smith said...

Great and Useful Article.

Online Java Training

Java Online Training India

Java Online Course

Java EE course

Java EE training

Best Recommended books for Spring framework

Java Interview Questions








Java Course in Chennai

Java Online Training India

Vũ Diệu Linh said...

I enjoyed on reading your blog post. Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article. Please visit my website, Friv 4000 Games is where all the free friv games.
Friv 4000