The Java String contains() searches a substring in the given string. It returns true
if substring are found in this string otherwise returns false
.
1. String contains() method
Use String.contains()
to find is a substring is present in given string or not. Please remember that this method is case sensitive.
1.1. Method syntax
The method internally takes help of indexOf() method to check the index of substring. If substring is present then index will be always greater than '0'
.
/** * @param substring - substring to be searched in this string * * @return - true if substring is found, * false if substring is not found */ public boolean contains(CharSequence substring) { return indexOf(s.toString()) > -1; }
1.2. ‘null’ is not valid method argument
String.contains() method does not accept 'null'
argument. It will throw NullPointerException
in case method argument is null.
Exception in thread "main" java.lang.NullPointerException at java.lang.String.contains(String.java:2120) at com.StringExample.main(StringExample.java:7)
2. String contains() example
Java program to find a substring is present in given string or not.
public class StringExample { public static void main(String[] args) { System.out.println("Hello World".contains("Hello")); //true System.out.println("Hello World".contains("World")); //true System.out.println("Hello World".contains("WORLD")); //false - case-sensitive System.out.println("Hello World".contains("Java")); //false } }
Program output.
true true false false
In this example, we learned to check is substring is present in given string using Java string contains() method.
References:
A Guide to Java String
String Java Doc
fullmoondweller
“s.toString()” in Method Syntax would be “substring.toString()”?