In Java, the split method on a String breaks the string into an array of substrings based on a regular expression (regex) delimiter. It returns a String[] containing the pieces between matches of the delimiter, and optionally limits how many pieces are produced.
Background: Why split() Exists
Before Java 1.4, splitting a string required manual parsing with StringTokenizer or index-based loops. String.split() was introduced in Java 1.4 as a convenience method that leverages the java.util.regex package internally. It quickly became the standard way to tokenize strings, though StringTokenizer remains available for legacy code. The method is part of the String class and is not static; you call it on an existing string instance.
How split() Works Under the Hood
When you call split(regex), Java compiles the regex into a Pattern and uses a Matcher to find matches. Each match acts as a separator; the text before the first match, between matches, and after the last match becomes an element in the resulting array. If the regex does not match anywhere, the array contains a single element: the original string.
The two overloads are:
String[] split(String regex)– splits on every match and removes trailing empty strings.String[] split(String regex, int limit)– controls the number of resulting elements and whether trailing empties are kept.
The limit parameter has three regimes:
- limit > 0: the pattern is applied at most
limit - 1times, so the array length is at mostlimit. The last element contains the unsplit remainder, including any delimiters. - limit = 0: the pattern is applied as many times as possible, and trailing empty strings are discarded. This is the default behavior of the one-argument version.
- limit < 0: the pattern is applied as many times as possible, and trailing empty strings are retained.
For example, "a,b,c".split(",") returns ["a", "b", "c"]. "a,b,c".split(",", 2) returns ["a", "b,c"]. "a,b,".split(",") returns ["a", "b"] (trailing empty removed), while "a,b,".split(",", -1) returns ["a", "b", ""].
Regex Delimiters and Special Characters
Because the argument is a regex, characters like ., |, *, +, ?, [, ], (, ), {, }, ^, $, and \ have special meanings. To split on a literal dot, you must escape it: split("\\."). To split on a pipe character, use split("\\|"). Alternatively, Pattern.quote() can wrap a literal string safely: split(Pattern.quote(".")).
Common regex constructs used as delimiters include:
\\s+– one or more whitespace characters (spaces, tabs, newlines).[,;]– a comma or semicolon.\\d+– one or more digits.\\b– a word boundary (rarely useful for splitting).
For example, splitting a sentence on whitespace: "Java is fun".split("\\s+") yields ["Java", "is", "fun"]. Splitting on multiple delimiters: "a,b;c".split("[,;]") yields ["a", "b", "c"].
Choosing the Right Approach: split() vs. Other Methods
While split() is convenient, it is not always the best choice. Consider these alternatives:
- StringTokenizer: faster for simple single-character delimiters, but does not support regex and is legacy. It also does not handle empty tokens well.
- Pattern.split(): if you reuse the same regex many times, compile a
Patternonce and call itssplit()method to avoid recompiling the regex on every call. This is more efficient in loops. - Scanner: useful for parsing input with multiple delimiters and hasNext methods, but heavier.
- Manual parsing: for very simple cases (e.g., splitting on a single character), a loop with
indexOfcan be faster and avoids regex overhead.
Also note that split() returns a new array each time; for large strings or frequent calls, the memory and CPU cost of regex compilation can matter.
Common Problems and Pitfalls
Several issues trip up developers using split():
- Unescaped regex metacharacters: splitting on
"."without escaping yields an empty array because the dot matches any character. Always escape or usePattern.quote(). - Trailing empty strings removed: the default behavior discards trailing empties, which can be surprising when parsing CSV lines with missing fields. Use a negative limit to keep them.
- Leading empty string: if the string starts with the delimiter, the first element is an empty string. For example,
",a,b".split(",")returns["", "a", "b"]. - Performance: compiling a regex for every split call is expensive. In hot loops, precompile a
Pattern. - Null input: calling
split()on a null reference throwsNullPointerException; the method itself does not accept null. - Empty regex:
split("")splits between every character, which is rarely intended.
A common misconception is that split() uses simple string matching. It does not—it always treats the argument as a regex. Even a single character like "|" is a regex alternation operator, so it must be escaped.
Practical Examples
Here are concrete examples illustrating typical usage:
- Split a CSV line:
"apple,banana,cherry".split(",")→["apple", "banana", "cherry"]. - Limit the number of parts:
"key=value=extra".split("=", 2)→["key", "value=extra"]. - Keep trailing empties:
"a,b,".split(",", -1)→["a", "b", ""]. - Split on whitespace:
" hello world ".trim().split("\\s+")→["hello", "world"](trim removes leading/trailing spaces). - Split on a literal dot:
"192.168.1.1".split("\\.")→["192", "168", "1", "1"].
These examples show how the limit parameter and regex escaping affect the output.
Frequently Asked Questions
Why does split(".") return an empty array?
Because the dot is a regex metacharacter that matches any character. When used as a delimiter, it matches every character, so the resulting array has no non-empty elements (trailing empties are removed). To split on a literal dot, escape it: split("\\.").
How do I split a string but keep the delimiters?
split() discards the delimiters. To keep them, you can use a regex with capturing groups and Matcher methods, or manually parse. Alternatively, use String.split() with a lookahead/lookbehind pattern, but that is advanced and may not work for all cases.
What is the difference between split(",") and split(",", -1)?
The one-argument version removes trailing empty strings. The version with a negative limit retains them. For example, "a,b,".split(",") gives ["a", "b"], while "a,b,".split(",", -1) gives ["a", "b", ""].
Is split() thread-safe?
Yes, String.split() is thread-safe because it creates a new Pattern and Matcher internally for each call. However, if you precompile a Pattern and share it, Pattern is thread-safe but Matcher is not.
Can split() return null?
No, split() always returns a non-null array. If the input string is empty, the result is an array with one element: the empty string (unless the regex matches the empty string, in which case behavior depends on the limit).
How do I split on a newline?
Use split("\\r?\\n") to handle both Windows and Unix line endings, or split("\\R") in Java 8+ which matches any line break.