This function is specially designed to check if a string ‘contains’ another string or not. If you’re new to this you might end up using it to find a ‘character’. But it won’t serve the purpose. In this article, we’ll address how java.lang.String.contains() is used, implemented and what exceptions can arise if not used carefully.

What is the contains() method?

You can use the contains(String key) method to “find” if a certain string “key” is present within a certain string or not. If “key” is found, “true” is returned. Else you will get a “false”.Java String contains() Method - 1

Internal Implementation

This method is already implemented by java.lang.String. You don’t have to implement this yourself. Here’s a quick explanation of it for your understanding.

public class ContainsMethod 
{
    public boolean contains(CharSequence key) 
    {  
        return indexOf(key.toString()) > -1;  
    } 
} 

Code Explanation

contains() method, takes a CharSequence as an input parameter. Which is later on converted to a “String”. Then this expression is computed indexOf(key.toString()) > -1;. Which means, if that “key” is found at any index ( “0” or greater ) then “true” is returned. And if the key is not found, then a “false” is returned.

How to use the contains() method?

Here’s how you can use it.

public class ContainsMethod {
    public static void main(String[] args) {

	String input = "A brown fox jumped over a lazy dog.";

	// check the containing strings
	System.out.println("input.contains(bro) = " + input.contains("bro"));
	System.out.println("input.contains(brown) = " + input.contains("brown"));
	System.out.println("input.contains(Brown) = " + input.contains("Brown"));

	System.out.println("input.contains(fox) = " + input.contains("fox"));
	System.out.println("input.contains(xof) = " + input.contains("xof"));
		
	System.out.println("input.contains(dog) = " + input.contains("dog"));
	System.out.println("input.contains(lazyy) = " + input.contains("lazyy"));
	System.out.println("input.contains(jumping) = " + input.contains("jumping"));
    }
}
Output
input.contains(bro) = true input.contains(brown) = true input.contains(Brown) = false // false because case-sensitive input.contains(fox) = true input.contains(xof) = false // false because order should be the same input.contains(dog) = true input.contains(lazyy) = false // false because whole substring not found input.contains(jumping) = false

Code Explanation

Please note, this method is case-sensitive for input parameters. So in the above snippet, you can observe when you search “brown” true is returned, whereas false is returned for “Brown”. Also, you’ll get true if you find “fox” and false for “xof” or “oxf” because the order of characters needs to be the same. Lastly, if you find “jump” or “jumped” you will get a true as the whole parameter is present in the “input” string. Whereas, if you check for “jumping” false is returned because the entire key (“jumping”) is not found.

Taking care of Exceptions

java.lang.String.contains() method results in a Null Pointer Exception if you forget to initialize the parameter string with some concrete value.

public class ContainsMethod {
    public static void main(String[] args) {

      String input = "Here is a test string.";
      String test = null;

	// check what happens if you look for a null string 
	System.out.println("input.contains(test) = " + input.contains(test));
	}
}
Output

Exception in thread "main" java.lang.NullPointerException
	at java.lang.String.contains(String.java:2133)
	at ContainsMethod.main(ContainsMethod.java:8)

Implications of Using Different CharSequence Types

One of the strengths of the contains() method lies in its ability to accept any implementation of the CharSequence interface. This makes it versatile for use with various types of character sequences, not just String objects.

What is a CharSequence?

The CharSequence interface represents a readable sequence of char values. Common implementations include:

  • String
  • StringBuilder
  • StringBuffer
  • Custom implementations of CharSequence

Example: Using StringBuilder with contains()

public class ContainsWithStringBuilder {
    public static void main(String[] args) {
        String str = "Hello World";
        StringBuilder sb = new StringBuilder("World");

        // Checking if the String contains the StringBuilder sequence
        System.out.println(str.contains(sb)); // Output: true
    }
}

In this example, the contains() method successfully identifies the sequence of characters in a StringBuilder, demonstrating its flexibility.

Example: Using Custom CharSequence

public class CustomCharSequence implements CharSequence {
    private final String data;

    public CustomCharSequence(String data) {
        this.data = data;
    }

    @Override
    public int length() {
        return data.length();
    }

    @Override
    public char charAt(int index) {
        return data.charAt(index);
    }

    @Override
    public CharSequence subSequence(int start, int end) {
        return data.subSequence(start, end);
    }

    @Override
    public String toString() {
        return data;
    }

    public static void main(String[] args) {
        String str = "Java Programming";
        CustomCharSequence customSeq = new CustomCharSequence("Java");

        // Checking if the String contains the custom CharSequence
        System.out.println(str.contains(customSeq)); // Output: true
    }
}

This example illustrates how a custom implementation of CharSequence can be seamlessly used with the contains() method.

Performance Considerations

While the contains() method works with all CharSequence types, the performance may vary depending on the implementation. For instance:

  • String: Typically efficient since it is immutable and optimized for string operations.
  • StringBuilder/StringBuffer: Slightly less efficient due to their mutable nature.
  • Custom implementations: Performance depends on the logic implemented in the CharSequence methods.

Case Sensitivity Behavior of the contains() Method

The contains() method is case-sensitive, meaning that it differentiates between uppercase and lowercase letters when performing a comparison. This behavior can lead to unexpected results if developers are not mindful of string casing.

Example 1: Case-Sensitive Match

public class ContainsCaseSensitiveExample {
    public static void main(String[] args) {
        String str = "Hello World";
        System.out.println(str.contains("World")); // Output: true
        System.out.println(str.contains("world")); // Output: false
    }
}

In this example, the contains() method returns true when the case matches ("World") but returns false when the case does not match ("world").

Example 2: Partial Case Mismatch

public class PartialCaseMismatchExample {
    public static void main(String[] args) {
        String str = "Java Programming";
        System.out.println(str.contains("Java")); // Output: true
        System.out.println(str.contains("java")); // Output: false
    }
}

Even a single character mismatch in case can cause the contains() method to return false.

Handling Case Sensitivity for Case-Insensitive Searches

If a case-insensitive search is desired, the contains() method alone is insufficient. A common approach is to convert both the original string and the substring to a common case (either lowercase or uppercase) before performing the comparison.

Using toLowerCase() for Case-Insensitive Search

public class CaseInsensitiveContainsExample {
    public static void main(String[] args) {
        String str = "Hello World";
        String substring = "world";

        // Convert both strings to lowercase for case-insensitive comparison
        boolean result = str.toLowerCase().contains(substring.toLowerCase());
        System.out.println(result); // Output: true
    }
}

By converting both the main string and the substring to lowercase, we ensure the comparison ignores case differences.

Using toUpperCase() for Case-Insensitive Search

public class CaseInsensitiveContainsWithUpperCase {
    public static void main(String[] args) {
        String str = "Java Programming";
        String substring = "programming";

        // Convert both strings to uppercase for case-insensitive comparison
        boolean result = str.toUpperCase().contains(substring.toUpperCase());
        System.out.println(result); // Output: true
    }
}

The toUpperCase() approach achieves the same result as toLowerCase(), allowing flexibility based on preference or context.

Conclusion

Contains() method provides a handy java utility to find any char-sequence or a string. We hope by the end of this post, you’re familiar with its use and implementation. For an even better understanding, you’re encouraged to roll up your sleeves and get to work. Creating error-free code comes with consistent effort. So let’s get it guys! You’re always welcome to get back here when you get stuck. Happy Coding. :)