Java String.contains() Method: How to Check for Substrings – Practical Examples
Java String.contains() Method: How to Check for Substrings
The String.contains() method in Java determines whether a specified sequence of characters appears within a string. It returns true if the substring exists, otherwise false. Because the result is a boolean, it is commonly used directly in if statements.
Method Signature
public boolean contains(CharSequence s)
Parameters
s – The character sequence to search for.
Return Value
Returns true if this string contains the specified sequence; otherwise false.
Exceptions
Throws NullPointerException if s is null.
Practical Example
Below is a complete example that demonstrates common usage patterns and highlights case sensitivity.
public class SampleString {
public static void main(String[] args) {
String strSample = "This is a String contains Example";
// Check for various substrings
System.out.println("Contains 'ing': " + strSample.contains("ing"));
System.out.println("Contains 'Example': " + strSample.contains("Example"));
System.out.println("Contains 'example': " + strSample.contains("example")); // case-sensitive
System.out.println("Contains 'is String': " + strSample.contains("is String"));
}
}
Output:
Contains 'ing': true
Contains 'Example': true
Contains 'example': false
Contains 'is String': false
When to Use contains()
Use contains() whenever you need to verify the presence of a substring within a larger string. Common scenarios include:
- Validating user input (e.g., checking for prohibited words)
- Parsing log entries or configuration strings
- Implementing simple search features
Using contains() in Conditional Statements
The method integrates seamlessly with if/else logic. Here’s a concise example:
public class IfExample {
public static void main(String[] args) {
String text = "Java string contains If else Example";
if (text.contains("example")) {
System.out.println("The keyword :example: is found in the given string");
} else {
System.out.println("The keyword :example: is not found in the string");
}
}
}
Output:
The keyword :example: is not found in the string
Java
- Encapsulation in Java: A Comprehensive Guide with Practical Example
- Master Java String Manipulation: Essential Functions, Methods, and Practical Examples
- Java String length() Method: How to Get a String’s Size (Example)
- Mastering Java String.indexOf(): Locating Substrings & Practical Examples
- Understanding Java String.charAt(): Syntax, Return Type, Exceptions, and a Practical Example
- Mastering Java's String compareTo() Method: Syntax, Use Cases, and Practical Examples
- Mastering Java’s String.endsWith(): How to Check String Suffixes with Examples
- Polymorphism in Java: A Comprehensive Guide with Practical Examples
- Java Abstraction: Mastering Abstract Classes, Methods, and Practical Examples
- Mastering Java's split() Method: A Practical Guide with Code Examples