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:
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.


Milan Vachhani said...

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

Unknown 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

Unknown 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

Richard Majece said...

As for me, information from https://essayclick.net/blog/sat-score will be useful to read for college students. It will help you to improve your SAT score

AjayKM said...

I have read your blog its very attractive and impressive. I like it your blog.


Liza said...

If you need writing help but don't know what service to choose - read https://top-papers.com/reviews/ to make the right decision

Darren Demers said...

Kuchi Jewels is a project of Gem & Gems which is a leading exporter since 2005 to onwards in all over the world. Our company has experienced, educated and motivated staff. Our main goal is to meet the international standard B2C and B2B export target with competitive prices and high quality products. pandora necklace canada , pandora necklace australia