Curious Minds

Clear answers to science and history questions

How Does split() Work in Java? String.split Explained

· 5 min read · Science

In Java, split() is a method on the String class that breaks a string into an array of substrings based on a regular expression you supply as the delimiter. For example, "a,b,c".split(",") returns the array ["a", "b", "c"]. It has two forms: split(String regex), which splits on every occurrence, and split(String regex, int limit), which lets you control how many times the split is applied and whether trailing empty strings are kept.

How split() Works Internally

Under the hood, split() delegates to the java.util.regex.Pattern class. When you call it, Java compiles your delimiter string into a Pattern and applies it to the string. This is why the argument is a regex rather than a plain literal, and why certain characters (like ., |, *, and $) need escaping to be treated literally.

The method scans the string left to right, finds each match of the pattern, and treats the text between matches as one element of the resulting array. If no match is found at all, the entire original string is returned as a single-element array.

The Two Signatures

  • public String[] split(String regex) — equivalent to calling split(regex, 0). It splits on every match and automatically discards trailing empty strings.
  • public String[] split(String regex, int limit) — the limit parameter controls the maximum number of resulting strings and how empty strings are handled.

The behavior of limit has three cases:

  • Positive limit: the pattern is applied at most limit - 1 times, so the array contains no more than limit elements. The last element holds everything remaining after the final split.
  • Zero: splits as many times as possible, and trailing empty strings are removed.
  • Negative limit: splits as many times as possible, and trailing empty strings are kept.

Practical Examples

Basic comma splitting:

String[] parts = "apple,banana,cherry".split(",");
// ["apple", "banana", "cherry"]

Splitting on any whitespace, with a limit:

String[] parts = "one two three four".split("\\\\s+", 2);
// ["one", "two three four"]

Keeping empty trailing fields with a negative limit:

String[] a = "a,b,,".split(",");    // ["a", "b"]
String[] b = "a,b,,".split(",", -1); // ["a", "b", "", ""]

Splitting on a literal dot (which must be escaped because it is a regex metacharacter):

String[] version = "1.8.0_292".split("\\\\.");
// ["1", "8", "0_292"]

Regex Escaping and Special Characters

Because the delimiter is a regular expression, these characters have special meanings and will not behave as literals unless escaped: . ? * + ^ $ ( ) [ ] { } | \

Two safe approaches:

  • Escape manually with a backslash, doubled in Java source: split("\\\\.") splits on a literal dot.
  • Use Pattern.quote() to treat the entire string literally: split(Pattern.quote("a|b")) splits on the exact text a|b.

You can also use character classes: split("[;,.]") splits on semicolons, commas, or periods, and inside brackets a dot is already literal.

Common Pitfalls and Problems

  • Trailing empty strings vanish. ",a,b,".split(",") returns ["", "a", "b"] — the leading empty string survives, but the trailing one is dropped. Use split(",", -1) if you need to preserve field positions, which matters for CSV-like data.
  • Unescaped regex metacharacters. "1.2".split(".") returns an empty array because . matches any character. Always escape.
  • NullPointerException. Calling split() on a null string throws an NPE, as does passing a null regex.
  • Empty leading splits. If the string starts with the delimiter, the first array element is an empty string, which can surprise code that assumes a value at index 0.
  • Repeated delimiters produce empties. "a,,b".split(",") yields ["a", "", "b"]. If you want to collapse runs of delimiters, use a quantifier like split(",+").

Performance Considerations

Each call to split() compiles the regex into a Pattern, which involves some overhead. For occasional calls this is negligible, but in tight loops it can add up. If you are splitting with the same delimiter many times, compile once and reuse:

Pattern p = Pattern.compile(",");
for (String line : lines) {
    String[] fields = p.split(line);
}

For the single-character case, Java has an internal fast path that avoids full regex machinery for simple patterns, so simple delimiters are already reasonably quick. Also note the method allocates a new array and new String objects on every call, so very large inputs naturally carry memory cost.

Alternatives to split()

  • Pattern.split() — the same mechanism with a precompiled pattern, better for repeated use.
  • StringTokenizer — an older class that splits on single characters. It is a legacy class retained for compatibility; the Java documentation recommends split() for new code.
  • String.indexOf() / substring() loops — manual parsing, fastest option for hot paths, but more code to maintain.
  • Matcher.results() with a find pattern — Java 9+ lets you stream matches, useful when you want to extract tokens by matching them rather than splitting on separators.
  • Real CSV/TSV parsers — for files with quoted fields containing delimiters, use a dedicated parser library rather than split(), which cannot handle quoting rules.

Frequently Asked Questions

What does split() return if the delimiter is not found?

The method returns an array containing the original string as its single element. It never returns an empty array in that case, though "".split(",") does return an array with one empty string, not a zero-length array.

Why does split() remove empty strings at the end?

With the default limit of 0, trailing empty strings are discarded by design, mainly so that splitting strings ending in a delimiter does not produce meaningless empty fields. If you need them, pass a negative limit such as -1.

How do I split a string into individual characters?

Use "abc".split(""), which returns ["a", "b", "c"]. For strings containing supplementary characters like emoji, be aware that split("") splits by code unit, so consider using codePoints() (Java 8+) instead.

Can I split on multiple different delimiters at once?

Yes. Use a character class or alternation in the regex: split("[,;\\\\s]+") splits on commas, semicolons, or whitespace, treating consecutive delimiters as one.

Is split() case-sensitive?

By default, yes. To make the delimiter case-insensitive, embed the flag: split("(?i)and") will split on "and", "AND", or "And".

Does split() modify the original string?

No. Strings in Java are immutable, so split() always leaves the original string untouched and returns a brand-new array of new String objects.

In this article
  1. How split() Works Internally
  2. The Two Signatures
  3. Practical Examples
  4. Regex Escaping and Special Characters
  5. Common Pitfalls and Problems
  6. Performance Considerations
  7. Alternatives to split()
  8. Frequently Asked Questions