Java String contains() Method

The contains() method in Java is used to check if a specified sequence of characters (a substring) exists within a given string. It returns true if the substring is found, otherwise it returns false.

Syntax:


public boolean contains(findStringFromOriginalString) 

Note:

  1. if the substring exists within the string then will show true
  2. if the substring does not exist within the string then will show false

Example:


public class Main {
    public static void main(String[] args) {
        // Example string
        String str = "How are you";
        
        // Check if the string contains the substring "you"
        boolean containsYou = str.contains("you");
        
        // Check if the string contains the substring "Hello"
        boolean containsHello = str.contains("Hello");
        
        System.out.println("Contains you: " + containsYou);  // Output: true
        System.out.println("Contains Hello: " + containsHello);    // Output: false
    }
}

Output:

Contains you: true
Contains Hello: false

contains method is a Case Sensitive

The contains() method is case-sensitive. That means “how” and “How” would be considered different strings.

Example:


public class Main {
    public static void main(String[] args) {
        String str = "How are you";
        
        // Check if the string contains "How"
        boolean containsHowWord = str.contains("How");
        
        // Check if the string contains "how" (small h)
        boolean containshowWord = str.contains("how");
        
        System.out.println("Contains 'How': "+ containsHowWord);  // Output: true
        System.out.println("Contains 'how': "+ containshowWord);  // Output: false
    }
}

Empty String

The contains() method will return true if the substring is an empty string because an empty string is considered to be contained within any string.


public class Main {
    public static void main(String[] args) {
        String str = "How are you";
        
        // Check if the string contains an empty string
        boolean containsEmpty = str.contains("");
        
        System.out.println("Contains empty string: " + containsEmpty);  // Output: true
    }
}