Use String.split("\s+") when you want to treat runs of whitespace as one separator, or split(" ") when you specifically want single literal spaces. Both return a String[], and you can pass a limit as a second argument to control how many pieces you get. The first form is the usual default because it tolerates the accidental double space or a tab. The second is correct when every space character should produce a boundary, including empty strings between adjacent spaces. Java has several other splitters for different needs, and picking the right one matters more than the one-liner suggests.
The two-line answer and why the choice matters
The core action is short:
split takes a regular expression, not a plain delimiter, so " " is a one-character regex matching an actual space, while "\s+" matches one or more whitespace characters (space, tab, newline, carriage return, form feed, and vertical tab). That difference decides what happens with messy input. Given "alpha beta" (two spaces), split(" ") returns ["alpha", "", "beta"], while split("\s+") returns ["alpha", "beta"]. Neither is wrong; they answer different questions.
The method returns a new array, or in rare cases a single-element array. It throws PatternSyntaxException if the regex is malformed, and NullPointerException if the string is null. Trimming first is often a good idea for user input, though it changes what an empty input yields.
Regular expressions first: what \s actually matches
In Java source code you write "\s" because the backslash itself needs escaping in a string literal. The regex \s matches a whitespace character as defined by Java's Pattern class: [ \t\n\x0B\f\r]. That is ASCII whitespace, not the broader Unicode set. If your text might contain non-breaking spaces or other Unicode space characters, \s will not catch them by default.
There's a fix. You can enable Unicode-aware predefined classes with the (?U) flag inside the regex:
Or you can use a POSIX class like "\p{javaWhitespace}+", which matches what Character.isWhitespace considers whitespace, or "\p{Zs}+" for Unicode space separators such as the non-breaking space. The tradeoff is portability of intent versus simplicity. For ordinary English text, \s+ is fine. For text from web forms, pasted documents, or non-Latin content, the Unicode-aware version prevents silent failures where a phrase stays glued together.
A subtle trap: \s+ collapses a newline too. If you split a multi-line string expecting only spaces as boundaries, you'll lose the line structure and get tokens joined differently than you might expect. Decide deliberately whether newlines should count as spaces.
Single space versus runs of whitespace
Consider this input:
input.split(" ") gives ["", "", "one", "two\tthree", "", "", "four", ""]. Every literal space boundary shows up, tabs do not split, and leading/trailing empty strings remain. input.split("\s+") gives ["", "one", "two", "three", "four"]. The leading run of whitespace becomes one leading empty string, and the trailing run is discarded (more on that below).
If you want clean tokens from unpredictable input, the second form plus a trim() is the practical choice:
If you want to preserve empty fields, which matters for parsing fixed-format records, use split(" ", -1). The negative limit keeps trailing empty strings, so a trailing space yields an empty last element. Without the negative limit, trailing empties are removed, which can silently change record length.
The limit parameter and what it changes
split(regex, limit) has three regimes worth knowing:
Positive limit n: the pattern is applied at most n−1 times, so the result has at most n elements, and the final element contains the rest of the string unsplit. "a b c d".split(" ", 2) gives ["a", "b c d"]. This is handy when only the first field is a key and the remainder is free text. Zero limit (the default): trailing empty strings are discarded. "a b ".split(" ") gives ["a", "b"]. Negative limit: no limit and no discarding. "a b ".split(" ", -1) gives ["a", "b", ""].
Two traps hide here. First, if the string is only the delimiter, " ".split(" ") returns an empty array with the default limit, not an array holding one empty string. Second, a string that is empty to begin with, "".split(" "), returns [""], not an empty array. Counting tokens from user input without checking these cases leads to off-by-one bugs and confusing blank filters.
Trimming, filtering, and keeping the results clean
trim() removes leading and trailing characters at or below U+0020, which covers ordinary whitespace but not the Unicode space separators mentioned earlier. strip() in Java 11 and later uses Character.isWhitespace and is a better fit for modern text. Combining strip() with the Unicode-aware split gives the cleanest result:
If you want to drop empties anywhere (not just at the edges) without changing the regex, stream and filter:
This is often clearer than tuning regexes and limits. One caveat: a stream over split allocates the array first, so it isn't saving memory versus filtering the array in a loop, but it reads better in most codebases.
Splitting repeatedly: Pattern and splitAsStream
String.split recompiles the regex each call. That's fine for occasional use. In a loop over thousands of lines, it adds up. Java's Pattern class lets you compile once:
For very large inputs, ws.splitAsStream(line) avoids materializing the entire array, but it still splits eagerly under the hood in common implementations. The genuine win is avoiding recompilation, measured as roughly a constant reduction in per-call cost; the exact gain depends on JVM version and input, so benchmark your own workload rather than trusting general claims.
StringTokenizer and the scanner-style alternatives are sometimes suggested. StringTokenizer is legacy: it doesn't support regexes, its API is unfriendly to modern code, and it can't preserve empty tokens. It's not the right tool for new work, and its name appears in old code mostly because it predates split. Don't migrate toward it.
split versus Scanner versus manual parsing
Java gives you several roles:
split: best for one-shot or looped splitting of strings you already have in memory. Scanner: best when you're consuming tokens from a stream (console, file, socket) and want lazy, incremental reads. scanner.useDelimiter("\s+") and hasNext()/next() avoids loading everything at once. The cost is that Scanner is comparatively slow for high-volume parsing; BufferedReader plus split or a manual parser often performs better. Manual loop: best when you need fine control, for example columns with embedded spaces, or when you want to avoid regex overhead on huge inputs. A loop over charAt that accumulates into a StringBuilder gives predictable performance and no allocation of regex machinery.
For CSV-like data with spaces as one possible separator, none of these alone is enough: you need quote-aware parsing, which split cannot do correctly with a simple regex. Reach for a dedicated library or a state-machine parser.
A worked example: the first word and the rest
Suppose you're parsing "NAME Alice Marie Smith" where the command is the first token and everything after the first space is a free-text argument. Use a limit:
If the input is just "NAME" with no argument, split(" ", 2) returns a one-element array, and parts throws ArrayIndexOutOfBoundsException. Check the length:
That's the success check most tutorials skip. Test three inputs: normal, no-argument, and extra-spaces ("NAME Alice", where the limit preserves the extra space in the argument). Decide whether that leading space in the argument is acceptable or should be trimmed; parts.strip() handles it.
When splitting goes wrong: symptoms and fixes
| Symptom | Likely cause | Fix |
|---|---|---|
| PatternSyntaxException: Unclosed character class | Regex like [\s] written as "[\s]" incorrectly | Use "\s+" or "[ \t]+" and count brackets |
| Empty strings in results | Literal single-space split with consecutive spaces | Use "\s+" or filter empties |
| Trailing empty element missing | Default zero limit discards trailing empties | Pass -1 as limit |
| ArrayIndexOutOfBoundsException | Assuming a fixed number of tokens | Check parts.length before indexing |
| Unicode spaces not split | \s is ASCII-only | Use "(?U)\s+" |
| Null pointer | Null input | Guard or use Optional on the source |
Start with the reversible check: print Arrays.toString(parts) and the input with input.length() to spot invisible characters. The commonest real-world failure is non-breaking space pasted from a web page; the fix is the Unicode-aware regex, not retyping the data.
Edge cases worth a test
A short set of test inputs catches almost every surprise:
The point isn't memorizing these; it's that two of them contradict beginners' intuition. Write the assertions once, and your future self won't rediscover them in production.
What to reach for in practice
For everyday work, input.strip().split("(?U)\s+") handles the realistic cases: extra spaces, tabs, and Unicode separators. Add , -1 when field counts matter. Use split(" ", n) when only the first boundary is meaningful. Use Pattern when a loop is hot, and reach for Scanner or manual parsing when the source is a stream or when quotes and escapes are involved. These are one-liners, but each encodes a decision about empty fields, trailing delimiters, and Unicode. Making that decision explicit is the whole skill.