In Java, contains() checks whether a character sequence appears as a contiguous substring. It returns true or false.
You pass the text to find. It is required. The search is case-sensitive. Need the index as well? Use indexOf().
Syntax
Call contains on the string you search in.
java
boolean ok = text.contains("Java");
Call
What it does
text.contains("Java")
Returns true when Java appears anywhere in text.
The parameter type is CharSequence, so String and StringBuilder both work.
Library declarations
java
public boolean contains(CharSequence sequence);
Parameters
Parameter
Description
sequence
Required. The substring to find. Do not pass null.
Return Value
Return Value
Description
true
The substring was found.
false
The substring was not found.
Java Examples
Example 1 — Basic Substring Check
See true and false when a sequence is present, missing, or differs only by case.
java
public class ContainsBasic {
public static void main(String[] args) {
String text = "CodeToFun teaches Java";
System.out.println(text.contains("Java"));
System.out.println(text.contains("Python"));
System.out.println(text.contains("code"));
}
}
Output
true
false
false
How It Works
First call."Java" appears → true.
Second call."Python" is absent → false.
Third call."code" fails because the real text starts with uppercase C.
Exact match. Matching is contiguous and case-sensitive.
Example 2 — Case-Insensitive Search
Normalize both sides with toLowerCase() before calling contains.
java
public class ContainsIgnoreCase {
public static void main(String[] args) {
String text = "Welcome to JAVA";
String needle = "java";
boolean found = text.toLowerCase().contains(needle.toLowerCase());
System.out.println(found);
}
}
Output
true
How It Works
Default fails. Plain contains("java") would be false.
Lower both sides. Normalize text and needle first.
Then search. Call contains on the normalized string.
Same letters match. Result is true ignoring case.
Example 3 — Simple Input Validation
Use contains for quick shape checks (beginner-level only).
java
public class ContainsValidate {
public static void main(String[] args) {
String email = "[email protected]";
if (email.contains("@") && email.contains(".")) {
System.out.println("Looks like an email shape");
} else {
System.out.println("Missing @ or .");
}
}
}
Output
Looks like an email shape
How It Works
Check for @. Require the at-sign somewhere in the text.
Check for a dot. Also require ..
Both pass. This sample address satisfies both.
Beginner check only. Real email validation needs stronger rules.
Frequently Asked Questions
contains() checks whether a substring appears in a string and returns true or false.
sequence is required. It is the text to find.
Yes. Convert both sides with toLowerCase() for an ignore-case check.
contains() returns boolean. indexOf() returns the starting index or -1.
Every string contains the empty sequence, so the result is true.