Java String contains()
In this article, we will look at contains()
method from string class in java, what is it used for, syntax, return value with example programs.
Java string
contains()
method is used to check if a string contains a sequence of characters or not.Syntax
contains()
method accepts an argument of type java.lang.CharSequence
, which represents a sequence of characters.CharSequence
is an interface, which is implemented by String
, StringBuffer and StringBuilder
classes. Thus, argument of contains()
method may be of any of these types. Its signature is
public boolean contains(CharSequence s)
Return Value
contains()
returns true
or false
values depending on the sequence of characters in the argument object occur in the string or not.
It returns
true
, if the argument string or set of characters are found in the source string.
true
, if the argument string or set of characters do not occur in the string on which contains()
is invoked.
Remember that the characters should be in the same sequence as the argument.
Java documentation for contains()
states,
Returns true if and only if this string contains the specified sequence of char values.
String contains() example
Below is an example of string contains()
method
String source = "codippa.com"; String search = ".com"; System.out.println(source.contains(search)); // true
String contains() implementation
contains()
method internally invokes another string class indexOf()
method, which returns the first index of matching string.
indexOf()
returns -1, if the supplied string cannot be found in the source string.
Thus, contains()
simply compares the value returned by indexOf()
with 0.
If the value from indexOf()
is greater than or equal to 0, this means that the string contains characters.
Below is the source code of contains()
public boolean contains(CharSequence s) { return indexOf(s.toString()) >= 0; }
contains()
performs case sensitive comparison. This means that the string to be checked should exist in the same case in source string, otherwise contains()
will return false
. Example, String source = "codippa.com"; String search = ".Com"; System.out.println(source.contains(search)); // false
Thus, the comparison by contains()
is not insensitive.
Hope the article on Java string contains()
method was useful.