String Array Split in Java: Methods, Examples, and Tips

How-to basics · Updated November 22, 2026

In Java, call String.split(regex) to divide text into a String[], such as String[] parts = text.split(","); for comma-separated values. The argument is a regular expression, not necessarily a literal delimiter, so characters such as a period need escaping when you mean them literally.

The Basic String Split

The split method belongs to String and returns an array of strings. It removes the delimiter matches from the input; the delimiter itself is not included in the resulting elements. A simple example is:

String colorsText = "red,green,blue";
String[] colors = colorsText.split(",");

After this code runs, colors contains three elements: red, green, and blue. You can access them by index, starting at zero, or loop over the array:

for (String color : colors) {
    System.out.println(color);
}

Use colors.length to find the number of elements. The result is already a String[]; there is no need to convert it from a list unless another part of your program specifically requires a collection. The original string is not modified because Java strings are immutable.

How the Split Pattern Works

String.split accepts a regular expression. Java looks for matches of that expression and uses those matches as boundaries between the returned pieces. For a comma or a colon, the regex is straightforward. For characters with a special meaning in regular expressions, a plain-looking delimiter may behave differently than expected.

For example, a period in a regex means “any character,” not a literal dot. This code therefore does not split only at periods:

String[] pieces = "one.two".split(".");

Escape the period for the regex engine, and escape the backslash again for Java’s string-literal syntax:

String[] pieces = "one.two".split("\\.");

The regex passed to split is \., which matches a literal period. This two-layer escaping is a common source of confusion: Java processes the string literal first, then the regular-expression engine interprets the resulting pattern.

Choosing the Limit Argument

Java also provides split(String regex, int limit). The limit controls how many pieces are returned and, importantly, what happens to empty pieces at the end. Understanding it helps avoid silently losing data.

  • split(regex) behaves like split(regex, 0). Trailing empty strings are discarded.
  • A positive limit sets the maximum number of returned elements. The final element contains the remaining unsplit text.
  • A negative limit keeps trailing empty strings. There is no maximum number of pieces imposed by the limit.

Suppose a line ends in a comma. With String[] fields = "oak,pine,".split(",");, the result contains oak and pine; the empty field after the final comma is discarded. If that empty field matters, use String[] fields = "oak,pine,".split(",", -1);. This result has three elements, and the last one is the empty string.

A positive limit is useful when the last part may itself contain the delimiter. For example, String[] parts = "name:notes:more notes".split(":", 2); returns name and notes:more notes. Only the first matching colon separates fields; the remaining text stays together in the final element.

Splitting on Literal Delimiters

For a single regex metacharacter, escape it for both Java and regex syntax. Common examples include a period, a vertical bar, and a backslash. The exact pattern depends on whether you intend a special regex operation or a literal character.

  • Split on a period: text.split("\\.").
  • Split on a vertical bar: text.split("\\|").
  • Split on one or more whitespace characters: text.split("\\s+").

If a delimiter comes from a variable and must be treated literally, use Pattern.quote rather than trying to escape every possible regex character yourself:

String delimiter = ".";
String[] parts = text.split(java.util.regex.Pattern.quote(delimiter));

Pattern.quote turns the supplied text into a literal regex pattern. This is especially helpful for user-provided separators, which could otherwise contain regex operators and change how the split behaves. If your program needs the regular-expression features intentionally, pass a regex pattern instead of quoting it.

Useful Examples for Common Input

Whitespace often separates words, but input may contain several spaces or tabs. A pattern such as \s+ matches one or more whitespace characters, so consecutive whitespace is treated as a single separator:

String line = "Java   arrays	are useful";
String[] words = line.trim().split("\\s+");

Here, trim() removes leading and trailing characters recognized by that method before splitting. Without trimming, leading whitespace can produce an empty first element, and trailing whitespace can affect the final piece. For broader Unicode whitespace handling, choose and test a pattern appropriate to the input and Java regex behavior rather than assuming every whitespace character is identical.

To split a line on semicolons while preserving empty fields, use a negative limit:

String row = "A12;;C14;";
String[] columns = row.split(";", -1);

This gives four fields: A12, an empty string, C14, and another empty string. Preserving empty values can be important when positions have meaning, such as a missing column in a simple delimited record. If your data format supports quoted separators, however, a basic split is not sufficient; see the alternatives section below.

Common Problems and Their Fixes

A frequent mistake is expecting a string that looks like a delimiter to be treated literally. Since the parameter is a regex, "|" means alternation rather than a literal vertical bar. Use "\\|" or Pattern.quote("|") when the actual character is the separator.

Another common surprise is losing trailing empty elements. This is the default behavior, not a failure to detect the final delimiter. Use split(regex, -1) when the number and position of empty fields must be retained. Conversely, if empty trailing values are not meaningful, the default behavior is often convenient.

Check for whitespace in each returned element when input is not normalized. A comma split of "red, green" produces red and green; the space remains because it is not part of the comma delimiter. You can trim individual values, or deliberately include optional surrounding whitespace in a regex such as \s*,\s*. Do not trim automatically if spaces are valid data in your application.

Also distinguish an empty field from a missing field. An empty string can be a valid value, whereas an absent array element means there was no corresponding piece. Decide which interpretation your program needs, and use a limit and validation rules that preserve it. Before reading an index, check the array length; malformed or unexpected input can produce fewer pieces than your code assumes.

When Split Is Not the Right Tool

split works well for simple separators and regular patterns, but it is not a complete parser for every text format. A CSV row can contain quoted values with commas inside them, escaped quotation marks, or line breaks inside a quoted field. Splitting such a row at every comma breaks values that are supposed to remain together. Use a CSV parser that implements the format’s quoting rules instead.

For repeated use of the same regex in performance-sensitive code, you can compile a Pattern once and call its split method:

java.util.regex.Pattern separator =
        java.util.regex.Pattern.compile("\\s+");
String[] words = separator.split(text);

This makes the pattern reusable and makes the regex explicit. For a one-off split, String.split is usually clearer. If you need to parse a structured language, nested content, or quoted records, use a parser designed for that format rather than building increasingly complex split patterns.

Frequently Asked Questions

Does Java split return a String array?
Yes. Both String.split(String regex) and String.split(String regex, int limit) return a String[].

How do I split a string by a dot in Java?
Use text.split("\\."). The Java string literal supplies the escaped period required for the regex to match a literal dot.

How do I keep empty values at the end?
Pass a negative limit, for example text.split(",", -1). The one-argument form discards trailing empty strings.

How do I split on multiple spaces?
Use text.split("\\s+") to match one or more whitespace characters. Consider trimming first if leading or trailing whitespace should not create an empty piece.

Can split parse CSV correctly?
Not in general. A simple comma split cannot account for commas inside quoted fields or the other rules of CSV. Use a CSV-aware parser for actual CSV data.

In short, choose the simplest regex that matches the intended separator, escape literal regex metacharacters, and select the limit based on whether empty trailing fields matter. Those choices make the resulting String[] predictable and help prevent subtle data-handling bugs.

Related

Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.

More in How-to basics

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.