DEV Community

Cover image for Mastering Java: How to Use `String.contains()` Effectively
suraj kumar
suraj kumar

Posted on

Mastering Java: How to Use `String.contains()` Effectively

Java is one of the most popular programming languages, widely used for web development, mobile applications, and enterprise software. One of the essential features of Java is its powerful String class, which provides multiple methods to manipulate and examine text. Among these methods, String.contains() is a simple yet highly useful tool for checking the presence of a substring within a larger string. In this blog, we will explore how String.contains() works, best practices, use cases, and alternatives for more complex scenarios.

What is String.contains()?

The String.contains() method in Java is used to check if a particular sequence of characters (substring) exists within another string. It is a method of the String class and returns a boolean value:

  • true if the substring is found
  • false if it is not found

Syntax:

public boolean contains(CharSequence sequence)
Enter fullscreen mode Exit fullscreen mode

Here, CharSequence can be a String, StringBuilder, StringBuffer, or any object that implements the CharSequence interface.

Example:

public class Main {
    public static void main(String[] args) {
        String sentence = "Java programming is fun!";
        boolean hasJava = sentence.contains("Java");
        System.out.println("Contains 'Java'? " + hasJava);
    }
}
Enter fullscreen mode Exit fullscreen mode

Output:

Contains 'Java'? true
Enter fullscreen mode Exit fullscreen mode

How String.contains() Works

Internally, String.contains() uses the indexOf() method to determine if the substring exists in the string. If indexOf() returns a value greater than or equal to 0, the substring is present; otherwise, it is absent.

This means that String.contains() is case-sensitive, and it checks for an exact match of characters.

Example (case sensitivity):

String text = "Hello World!";
System.out.println(text.contains("hello")); // false
System.out.println(text.contains("Hello")); // true
Enter fullscreen mode Exit fullscreen mode

Common Use Cases

1. Searching User Input

You can use contains() to validate if a user has entered a specific keyword or command.

Scanner scanner = new Scanner(System.in);
System.out.println("Enter your message:");
String input = scanner.nextLine();

if (input.contains("help")) {
    System.out.println("Support information displayed.");
} else {
    System.out.println("No help requested.");
}
Enter fullscreen mode Exit fullscreen mode

2. Filtering Data

contains() is often used to filter lists or arrays based on text content.

String[] fruits = {"apple", "banana", "cherry", "pineapple"};
for (String fruit : fruits) {
    if (fruit.contains("apple")) {
        System.out.println(fruit);
    }
}
Enter fullscreen mode Exit fullscreen mode

Output:

apple
pineapple
Enter fullscreen mode Exit fullscreen mode

3. Validating Emails or URLs

You can check if an email contains the @ symbol or if a URL contains a specific domain.

String email = "user@example.com";
if (email.contains("@")) {
    System.out.println("Valid email format.");
}
Enter fullscreen mode Exit fullscreen mode

Best Practices

  1. Trim Input: Remove leading and trailing spaces to avoid false negatives.
String input = "  Java  ";
System.out.println(input.trim().contains("Java")); // true
Enter fullscreen mode Exit fullscreen mode
  1. Case Insensitive Checks: Convert strings to lowercase or uppercase for case-insensitive searches.
String sentence = "Java Programming";
System.out.println(sentence.toLowerCase().contains("java")); // true
Enter fullscreen mode Exit fullscreen mode
  1. Avoid Null Strings: Always check if the string is not null before using contains() to prevent NullPointerException.
String text = null;
if (text != null && text.contains("Java")) {
    System.out.println("Found");
}
Enter fullscreen mode Exit fullscreen mode

Alternatives to String.contains()

While contains() is very convenient, there are other methods you can use depending on your requirements:

  1. indexOf(): Returns the index of the first occurrence of the substring.
String str = "Java Programming";
if (str.indexOf("Java") >= 0) {
    System.out.println("Substring found!");
}
Enter fullscreen mode Exit fullscreen mode
  1. Regular Expressions: Use matches() or Pattern/Matcher for advanced pattern matching.
String str = "Hello123";
if (str.matches(".*\\d.*")) { // checks if string contains any digit
    System.out.println("Contains number");
}
Enter fullscreen mode Exit fullscreen mode
  1. Apache Commons StringUtils: Provides more flexible string operations.
import org.apache.commons.lang3.StringUtils;
String str = "Java Programming";
System.out.println(StringUtils.containsIgnoreCase(str, "java")); // true
Enter fullscreen mode Exit fullscreen mode

Performance Considerations

String.contains() is efficient for small strings and simple checks. However, for large-scale searches or repeated checks, consider the following:

  • Convert the target string to lowercase/uppercase once instead of repeatedly calling toLowerCase() inside a loop.
  • Use compiled regular expressions for repeated pattern checks.
  • For massive datasets, consider indexing or other optimized search structures.

Conclusion

String.contains() is one of Java’s simplest and most frequently used methods for substring search. Its simplicity, readability, and direct boolean output make it ideal for user input validation, filtering data, and basic text processing. By understanding its behavior, limitations, and alternatives, you can use it effectively in real-world Java applications. Remember to handle nulls, manage case sensitivity, and choose alternatives like indexOf() or regex for more complex scenarios. Mastering this small but powerful method is a step toward becoming proficient in Java string manipulation.

Top comments (0)