Java String contains() example

In this guide, you will learn about the String contains() method in Java programming and how to use it with an example.

1. String contains() Method Overview

Definition:

The contains() method in Java's String class is used to check if a particular sequence of characters is present within the string.

Syntax:

str1.contains(sequence)

Parameters:

- sequence: The sequence of characters to be checked within str1.

Key Points:

- The method returns true if the character sequence is present in the string, and false otherwise.

- It's case-sensitive, meaning "Hello" and "hello" are considered different sequences.

- If the sequence is empty, the method will always return true.

- The method throws a NullPointerException if the specified sequence is null.

2. String contains() Method Example

public class ContainsExample {
    public static void main(String[] args) {
        String phrase = "Java Programming is fun!";

        // Checking for presence of a sequence in the string
        boolean containsJava = phrase.contains("Java");
        System.out.println("Does the phrase contain 'Java'? " + containsJava);

        // Checking for a sequence that is not present
        boolean containsPython = phrase.contains("Python");
        System.out.println("Does the phrase contain 'Python'? " + containsPython);

        // Attempting to check for a null sequence
        try {
            phrase.contains(null);
        } catch (NullPointerException e) {
            System.out.println("Error: Cannot check for a null sequence.");
        }
    }
}

Output:

Does the phrase contain 'Java'? true
Does the phrase contain 'Python'? false
Error: Cannot check for a null sequence.

Explanation:

In the provided example, we use the contains() method to check for the presence of certain sequences within our string. 

First, we verify if "Java" is present, which it is, so the output is true

Next, we check for "Python", which isn't present, so the output is false

Finally, we intentionally check for a null sequence to demonstrate the NullPointerException that occurs, and we handle this exception in the catch block, printing an appropriate error message.

Related Java String Class method examples

Comments