YouTip LogoYouTip

Java String Contains

## Java String contains() Method The `contains()` method of the Java `String` class is used to check whether a string contains a specified sequence of characters. It is a highly efficient, built-in utility for performing substring searches without the need for complex regular expressions or manual index scanning. --- ### Syntax ```java public boolean contains(CharSequence chars) ``` ### Parameters * **`chars`**: The sequence of characters to search for. This parameter accepts any class implementing the `CharSequence` interface, such as `String`, `StringBuilder`, or `StringBuffer`. ### Return Value * Returns **`true`** if the string contains the specified sequence of characters. * Returns **`false`** otherwise. --- ### Code Example The following example demonstrates how to use the `contains()` method to search for different substrings within a target string: ```java public class Main { public static void main(String[] args) { String myStr = "Runoob"; // Check if the string contains the substring "Run" System.out.println(myStr.contains("Run")); // Output: true // Check if the string contains the single character "o" System.out.println(myStr.contains("o")); // Output: true // Check if the string contains the character "s" System.out.println(myStr.contains("s")); // Output: false } } ``` **Output:** ```text true true false ``` --- ### Key Considerations When using the `contains()` method, keep the following points in mind: 1. **Case Sensitivity** The `contains()` method is **case-sensitive**. For example, `"Hello World".contains("world")` will return `false` because of the lowercase "w". If you need a case-insensitive check, convert both strings to lowercase first: ```java String source = "Hello World"; boolean result = source.toLowerCase().contains("world"); // Returns true ``` 2. **NullPointerException** If you call `contains()` on a `null` string object, or if you pass `null` as the argument, Java will throw a `NullPointerException`. Always ensure your variables are initialized or perform a null check beforehand: ```java String source = "Hello"; String searchStr = null; if (source != null && searchStr != null) { boolean found = source.contains(searchStr); } ``` 3. **Under the Hood** Internally, the `contains()` method calls `indexOf(CharSequence.toString())`. If `indexOf` returns `0` or greater (indicating the substring was found), `contains()` returns `true`.
← Java Hashmap ClearJava Arraylist Replaceall β†’