Java String contains() method example

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(
	at com.StringExample.main(

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.


In this example, we learned to check is substring is present in given string using Java string contains() method.


A Guide to Java String
String Java Doc

Leave a Reply

1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial