1. Introduction
The contains()
method is a useful utility provided by the String
class in Java. It allows you to check if a particular substring is present within a given string. This method returns a boolean value, true
if the substring is found, and false
otherwise. The contains()
method is case-sensitive, meaning it considers the exact case of the characters in the substring.
2. Syntax
The syntax for the contains()
method is as follows:
javapublic boolean contains(CharSequence sequence)
3. Parameters
sequence
: The sequence of characters to be checked for existence in the string.
4. Return Value
true
if the specified substring is present in the string.false
if the specified substring is not found in the string.
5. Example
Let's see a code example to understand the usage of the contains()
method:
javapublic class StringContainsExample {
public static void main(String[] args) {
String mainString = "Hello, World!";
String substring1 = "Hello";
String substring2 = "world"; // Note the lowercase 'w'
// Check if the mainString contains substring1
boolean containsSubstring1 = mainString.contains(substring1);
System.out.println("Contains 'Hello': " + containsSubstring1); // Output: Contains 'Hello': true
// Check if the mainString contains substring2
boolean containsSubstring2 = mainString.contains(substring2);
System.out.println("Contains 'world': " + containsSubstring2); // Output: Contains 'world': false
}
}
6. Explanation
- In this example, we have a
mainString
with the value"Hello, World!"
. - We then define two substrings,
substring1
with the value"Hello"
andsubstring2
with the value"world"
. - We use the
contains()
method to check ifmainString
contains each of the substrings. - The first check (
mainString.contains(substring1)
) returnstrue
because"Hello"
is present inmainString
. - The second check (
mainString.contains(substring2)
) returnsfalse
because"world"
(with a lowercase 'w') is not present inmainString
. - It is important to note that the
contains()
method is case-sensitive. If you need to perform a case-insensitive check, you can convert both the main string and the substring to lowercase or uppercase before calling thecontains()
method.
7. Conclusion
The contains()
method in Java is a convenient way to check if a specific substring exists within a given string. It is a simple yet powerful tool for string manipulation and searching. Remember to consider the case-sensitivity of the method when using it in your applications.
0 Comments