Java string contains() Method
Photo Credit to CodeToFun
đ Introduction
In Java programming, manipulating strings is a common and crucial task.
The contains()
method is a built-in method in the java.lang.String class that checks whether a particular sequence of characters (substring) is present within the string.
In this tutorial, we'll explore the usage and functionality of the contains()
method in Java.
đĄ Syntax
The syntax for the contains()
method is straightforward:
public boolean contains(CharSequence sequence)
- sequence: The substring that you want to check for within the string.
đ Example
Let's dive into an example to illustrate how the contains()
method works.
public class StringContainsExample {
public static void main(String[] args) {
String text = "Hello, Java Programming!";
// Check if the string contains a specific substring
boolean containsSubstring = text.contains("Java");
// Output the result
System.out.println("Does the string contain 'Java'? " + containsSubstring);
}
}
đģ Output
Does the string contain 'Java'? true
đ§ How the Program Works
In this example, the contains()
method is used to check if the string "Hello, Java Programming!" contains the substring "Java" and prints the result.
âŠī¸ Return Value
The contains()
method returns a boolean value: true if the specified substring is found in the original string, and false otherwise.
đ Common Use Cases
The contains()
method is particularly useful when you need to determine whether a specific sequence of characters is present within a larger string. It simplifies tasks such as searching for keywords, validating input, or extracting relevant information.
đ Notes
- The
contains()
method is case-sensitive. If you need a case-insensitive search, you can convert the string and the substring to lowercase (or uppercase) using the toLowerCase() or toUpperCase() methods before callingcontains()
.
đĸ Optimization
The contains()
method is already optimized for efficient string searching. However, for large strings and frequent searches, consider storing the result in a variable if you need to use it multiple times to avoid redundant computations.
đ Conclusion
The contains()
method in Java is a valuable tool for checking the presence of a substring within a string. It provides a simple and effective way to perform this task, enhancing the versatility and readability of your code.
Feel free to experiment with different strings and substrings to explore the behavior of the contains()
method in various scenarios. Happy coding!
đ¨âđģ Join our Community:
Author
For over eight years, I worked as a full-stack web developer. Now, I have chosen my profession as a full-time blogger at codetofun.com.
Buy me a coffee to make codetofun.com free for everyone.
Buy me a Coffee
If you have any doubts regarding this article (Java string contains() Method), please comment here. I will help you immediately.