Wildcard Matching Implementation in Java
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Wildcard Matching runs in O(n*m) time and O(n*m) space, in Java as in every other language.
- ✓The JDK ships a glob engine on the filesystem API: FileSystems.getDefault().getPathMatcher("glob:*.java") returns a PathMatcher whose matches(Path) answers the question.
- ✓Reviewers want charAt in the loop and reject substring, which copies the character data on every call rather than sharing a backing array.
- ✓The Java trap: The idiomatic three-state memo, Boolean[][] where null means 'not yet computed', is a trap that only Java sets.
- ✓boolean[][] is an array of array objects: an n by m table is n + 2 separate heap objects, n + 1 row arrays plus the outer array of references, each with its own header, so the rows can land far apart and the DP walks cold cache lines.
What Wildcard Matching actually is
Wildcard Matching in Java: what you actually reach for
Java implementation
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
public final class Wildcard {
private Wildcard() {}
public static boolean isMatch(String s, String p) {
int n = s.length(), m = p.length();
boolean[] prev = new boolean[m + 1];
boolean[] cur = new boolean[m + 1];
prev[0] = true;
for (int j = 1; j <= m; j++) {
prev[j] = prev[j - 1] && p.charAt(j - 1) == '*';
}
for (int i = 1; i <= n; i++) {
char sc = s.charAt(i - 1);
cur[0] = false;
for (int j = 1; j <= m; j++) {
char pc = p.charAt(j - 1);
if (pc == '*') cur[j] = cur[j - 1] || prev[j];
else cur[j] = (pc == '?' || pc == sc) && prev[j - 1];
}
boolean[] t = prev; prev = cur; cur = t;
}
return prev[m];
}
public static boolean glob(String pattern, String name) {
PathMatcher pm = FileSystems.getDefault().getPathMatcher("glob:" + pattern);
return pm.matches(Path.of(name));
}
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Java-specific trap
Performance in Java, beyond the O(n*m)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Java type or library should I use for Wildcard Matching?
The JDK ships a glob engine on the filesystem API: FileSystems.getDefault().getPathMatcher("glob:*.java") returns a PathMatcher whose matches(Path) answers the question. Its documented grammar covers '*', '?', '**' for crossing directory boundaries, '[]' classes and '{a,b}' alternation, with '\\' as the escape. Files.newDirectoryStream(dir, "*.java") takes the same syntax directly. Note the signature: PathMatcher.matches takes a Path, not a String, so a plain name has to go through Path.of or Paths.get first. For non-path strings, java.util.regex.Pattern is the tool.
What is the most common Java mistake when implementing Wildcard Matching?
The idiomatic three-state memo, Boolean[][] where null means 'not yet computed', is a trap that only Java sets. Writing if (memo[i][j]) auto-unboxes, and on an unvisited cell that unboxes null and throws NullPointerException from a line containing no explicit dereference. Switching the memo to HashMap<Integer, Boolean> does not save you either: keys above 127 fall outside the Integer cache, so every cell allocates a fresh box and the memo that was meant to cut work adds an object per state. Use primitive boolean[][] plus a separate visited[][], or byte[][] with 0, 1, 2.
How does Wildcard Matching actually perform in Java?
boolean[][] is an array of array objects: an n by m table is n + 2 separate heap objects, n + 1 row arrays plus the outer array of references, each with its own header, so the rows can land far apart and the DP walks cold cache lines. One flat boolean[] of (n + 1) * (m + 1), or two swapped rows, keeps it contiguous. A boolean element occupies a byte, not a bit. Bounds checks in the inner loop are eliminated by C2 once the loop bound is provably the array length, but that only happens after the method is hot, so any measurement without JMH and a warmup phase reports interpreter and C1 numbers instead of steady state. Time complexity is O(n*m) and space is O(n*m).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialIf you are a student, see what Devin offers students for free on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.