Some time you want to check if one String contains another String or
SubString or not e.g. "HelloWorld" contains "Hello" and
"World" SubString.
There are many ways to check SubString in String in Java e.g. contains(), indexOf() or matches() method of java.lang.String class. In
our last article we have seen how
to use matches method of String class with regular expression and In this
article we will see example of contains() and indexOf() method to
check any String or SubString in Java. contains and indexOf method are defined in
java.lang.String class and used to check if String contains a
particular SubString or not, only difference between contains() and indexOf() method is
that, contains is added in Java 5 along with String matches() method
while indexOf() is as old as equals(),
hashCode
and compareTo().
Another difference between contains() and indexOf() method is
that contains() return boolean value e.g. true if String contains
SubString and false if String doesn't contains SubString but indexOf() return int
value, which is actually index of SubString i.e. starting location. indexOf() return -1
if source String does not contain SubString
in Java.