Check Substring in Java
Problem
A substring check determines whether one string appears anywhere inside another, as a contiguous sequence of characters.
Given two strings, determine whether the second is a substring of the first.
Java Program
public class SubstringCheck {
public static void main(String[] args) {
String str = "Hello World";
String sub = "World";
boolean found = false;
// Slide a window of sub's length across str, comparing at each position
for (int i = 0; i <= str.length() - sub.length(); i++) {
if (str.substring(i, i + sub.length()).equals(sub)) {
found = true;
break; // match found, no need to keep scanning
}
}
System.out.println("Contains substring: " + found);
}
}Output
Core Logic
Sliding a window the length of the target string across every starting position, and comparing at each one, finds a match the same way String.contains() would internally.
- 1The loop tries every starting index
ifrom0up tostr.length() - sub.length(), the last position wide enough to fitsub. - 2At each position,
str.substring(i, i + sub.length())extracts a window the same length assub. - 3
.equals(sub)compares that window against the target string. - 4The first matching window sets
foundtotrueandbreakexits immediately.
"Hello World" and "World", the window at index 6 — "World" — matches, so found becomes true.Key Point: This is the brute-force algorithm that a method like contains() conceptually performs — trading the convenience of a built-in call for seeing exactly how the search works.
Why: Each of the up to n candidate positions requires allocating and comparing a new substring of length m, so the work multiplies across positions and comparison length.
Key Concepts
Approach 2: Using contains()
public class SubstringCheckBuiltin {
public static void main(String[] args) {
String str = "Hello World";
String sub = "World";
// contains() already implements an efficient substring search internally
boolean found = str.contains(sub);
System.out.println("Contains substring: " + found);
}
}
Output
Core Logic
In real code, there's no reason to write the sliding window yourself — contains() already implements this search internally.
- 1
str.contains(sub)takes the target string directly and returns a boolean. - 2Internally, it performs the same kind of position-by-position search as the manual version, just already written and tested.
- 3No explicit loop, substring extraction, or comparison is needed in your own code.
"Hello World".contains("World") returns true in a single call.Key Point: This is the version to actually use — the manual sliding-window loop exists only to show what contains() is conceptually doing under the hood.
Why: contains() still performs the same kind of scan internally, but that scan happens inside the JDK — no manual substring allocation happens in your own code.