The String.contains()
method in Java is used to check if a specified sequence of characters exists within a string.
Table of Contents
- Introduction
contains
Method Syntax- Examples
- Basic Usage
- Case Sensitivity
- Using
contains
with Special Characters - Real-World Use Case
- Conclusion
Introduction
The String.contains()
method is a member of the String
class in Java. It allows you to determine if a given substring is present within the string. This is particularly useful for searching and validation purposes.
contains() Method Syntax
The syntax for the contains
method is as follows:
public boolean contains(CharSequence s)
- s: The sequence of characters to search for.
Examples
Basic Usage
The contains
method can be used to check if a string contains a specified sequence of characters.
Example
public class ContainsExample {
public static void main(String[] args) {
String str = "Welcome to Java";
boolean result = str.contains("Java");
System.out.println("Contains 'Java': " + result);
}
}
Output:
Contains 'Java': true
Case Sensitivity
The contains
method is case-sensitive, meaning it will only return true if the exact sequence, including case, is found.
Example
public class CaseSensitiveExample {
public static void main(String[] args) {
String str = "Welcome to Java";
boolean result1 = str.contains("java");
boolean result2 = str.contains("Java");
System.out.println("Contains 'java': " + result1);
System.out.println("Contains 'Java': " + result2);
}
}
Output:
Contains 'java': false
Contains 'Java': true
Using contains
with Special Characters
The contains
method can also be used with strings containing special characters.
Example
public class SpecialCharactersExample {
public static void main(String[] args) {
String str = "Welcome to Java @2021!";
boolean result = str.contains("@2021");
System.out.println("Contains '@2021': " + result);
}
}
Output:
Contains '@2021': true
Real-World Use Case
Example: Validating User Input
One common use case for contains
is validating user input, such as checking if an email address contains the "@" symbol.
public class ValidateEmailExample {
public static void main(String[] args) {
String email = "user@example.com";
if (email.contains("@")) {
System.out.println("Valid email address.");
} else {
System.out.println("Invalid email address.");
}
}
}
Output:
Valid email address.
In this example, the contains
method is used to check if the email address contains the "@" symbol, which is a basic validation step.
Conclusion
The String.contains()
method in Java is used for checking if a specified sequence of characters is present within a string. It is case-sensitive and works with strings containing special characters. This method is particularly useful for searching and validating strings in various applications. By understanding and utilizing the contains
method, you can efficiently manage string validation and searching in your Java programs.