Java String split() Method with Example

⚡ Smart Summary

Split a String in Java using the split() method, which breaks text wherever a delimiter matches and returns the pieces as a String array. An optional limit argument caps how many pieces are produced, leaving the remainder intact.

  • 🧩 Return Type: split() returns String[], never a single String, so the result must be assigned to an array.
  • 🔤 Delimiter Is Regex: The argument is a regular expression, so characters such as the dot and pipe need escaping.
  • 🔢 Limit Argument: Passing a limit of 3 produces two split pieces and keeps the rest of the text as the final element.
  • Whitespace Pattern: The pattern \\s matches any single whitespace character, which splits a sentence into words.
  • 🕳️ Trailing Blanks: Empty trailing fields are discarded unless a negative limit is supplied.
  • 🔁 Reading Results: A standard for loop over the array length prints each piece in order.

Java String split() Method

What is split() string in Java?

The split() method allows you to break a string based on a specific Java string delimiter. Most often the delimiter is a space or a comma (,) at which you want to break the string.

split() function syntax

public String[] split(String regex)
public String[] split(String regex, int limit)

⚠️ Note on the return type: split() returns a String[] array, not a single String. Assigning the result to a plain String variable fails to compile with an incompatible-types error, which is the most frequent mistake beginners make with this method.

Parameter

  • Regex: the regular expression applied to the text or string.
  • Limit: the maximum number of values in the resulting array. If it is omitted or zero, every substring matching the regex is returned.

How to Split a String in Java with Delimiter

The example below shows how to split a string in Java with a delimiter.

Suppose we have a string variable named strMain formed of a few words — Alpha, Beta, Gamma, Delta, Sigma — all separated by a comma (,).

 Split a String in Java

Here if we want all individual strings, the best possible pattern would be to split it based on the comma. So we will get five separate strings as follows:

  • Alpha
  • Beta
  • Gamma
  • Delta
  • Sigma

Use the string split method in Java against the string that needs to be divided, and provide the separator as an argument.

In this Java split string by delimiter case, the separator is a comma (,) and the result of the Java split string by comma operation will give you an array split.

class StrSplit{
  public static void main(String []args){
   String strMain = "Alpha, Beta, Delta, Gamma, Sigma";
    String[] arrSplit = strMain.split(", ");
    for (int i=0; i < arrSplit.length; i++)
    {
      System.out.println(arrSplit[i]);
    }
  }
}

The loop in the code just prints each Java split string from the array after the split function in Java, as shown below.

Expected Output:

Alpha
Beta
Delta
Gamma
Sigma

Example: Java String split() method with regex and length

Consider a situation where you require only the first ‘n’ elements after the split function in Java, but want the rest of the string to remain as it is. An output something like this:

  1. Alpha
  2. Beta
  3. Delta, Gamma, Sigma

This can be achieved by passing another argument along with the split() operation in Java, and that will be the limit of strings required.

Consider the following code of the split method in Java:

class StrSplit2{
  public static void main(String []args){
   String strMain = "Alpha, Beta, Delta, Gamma, Sigma";
    String[] arrSplit_2 = strMain.split(", ", 3);
    for (int i=0; i < arrSplit_2.length; i++){
      System.out.println(arrSplit_2[i]);
    }
  }
}

Expected Output:

Alpha
Beta
Delta, Gamma, Sigma

Note that a limit of 3 produces exactly three elements: the first two separators are honoured, and everything after the second separator is kept together as the third element.

How to Split a string in Java by Space

Consider a situation where you want to split a string by space. Here we have a split string Java variable named strMain formed of a few words: Welcome to Guru99.

public class StrSplit3{
public static void main(String args[]){
String strMain = "Welcome to Guru99";
String[] arrSplit_3 = strMain.split("\\s");
    for (int i=0; i < arrSplit_3.length; i++){
      System.out.println(arrSplit_3[i]);
    }
  }
}

Expected Output:

Welcome
to
Guru99

The pattern \\s matches a single whitespace character. Use \\s+ instead when words may be separated by more than one space, otherwise each extra space produces an empty element.

How to Keep Empty Strings When Splitting in Java

One behaviour of split() surprises almost everyone the first time they meet it: trailing empty strings are silently thrown away. Splitting "a,b,," on a comma returns two elements, not four, because the default limit of zero discards every empty field at the end of the array.

This matters whenever the data is positional — a CSV row, for instance, where a missing value at the end still occupies a column. Losing those blanks shifts every downstream index.

Passing a negative limit keeps them:

String row = "Alpha,Beta,,";

// Default: trailing empty fields removed -> length 2
String[] a = row.split(",");
System.out.println(a.length);        // prints 2

// Negative limit: every field preserved -> length 4
String[] b = row.split(",", -1);
System.out.println(b.length);        // prints 4

Three rules cover every case. A limit of zero, which is the default, applies the pattern as many times as possible and then drops trailing empty strings. A positive limit applies the pattern at most limit minus one times, so the final element holds the untouched remainder, exactly as the earlier example with a limit of 3 demonstrated. A negative limit applies the pattern as many times as possible and keeps every empty field, including the trailing ones.

Leading empty strings behave differently again: splitting ",a,b" always yields an empty first element regardless of the limit, because the pattern matches at position zero. Guard against it by trimming the input, or by filtering the resulting array before use.

split() vs StringTokenizer vs Pattern.split(): Which to Use

Java offers three ways to break a string into pieces. They differ in the kind of delimiter each accepts, in what they return, and in whether the pattern is compiled once or recompiled on every call, which matters once splitting happens inside a loop.

Aspect String.split() StringTokenizer Pattern.split()
Delimiter Regular expression Set of single characters Regular expression
Returns String[] Tokens via an enumeration String[]
Pattern compiled On every call Not applicable Once, then reused
Keeps empty fields Only with a negative limit Never Only with a negative limit
Status Recommended Legacy, retained for compatibility Recommended in loops

Use String.split() for ordinary one-off work, since it is the shortest to write and reads clearly. Pre-compile with Pattern.compile(",").split(text) when splitting inside a loop, because the regular expression is then compiled a single time rather than on every iteration. Avoid StringTokenizer in new code; it remains only for backward compatibility.

Common Java split() Errors and How to Fix Them

Nearly every problem with split() traces back to one of two causes: the argument is a regular expression rather than a literal string, or the limit rules described above are discarding fields unexpectedly. Each error below names its symptom and its fix.

  • Splitting on a dot returns an empty array: "1.2.3".split(".") matches every character, because the dot is a regex wildcard. Escape it as split("\\.").
  • Splitting on a pipe behaves oddly: the pipe means alternation in regex. Escape it as split("\\|").
  • Incompatible types error: the result was assigned to a String. Declare the variable as String[].
  • Unexpected empty first element: the delimiter appears at the start of the input. Trim the string first.
  • Missing values at the end: trailing empty fields were discarded by the default limit. Pass -1 as the second argument.
  • NullPointerException: split() was called on a null reference. Check for null before splitting, as the method cannot handle it.

FAQs

Use a character class, as in split("[,;]"), which breaks on either a comma or a semicolon. Alternation also works: split(",|;").

Yes. Wrap the array with Arrays.asList(text.split(",")) for a fixed-size view, or new ArrayList<>(Arrays.asList(...)) when the list needs to be modified afterwards.

Yes. AI tools produce a working pattern from a described format and explain each token. Test the result against edge cases such as empty fields and quoted values before trusting it.

AI assistants identify whether the cause is an unescaped metacharacter, a discarded trailing field, or a leading delimiter, which are the three explanations for an unexpected array length.

Only for simple data. It cannot handle commas inside quoted fields or embedded line breaks, so a dedicated CSV library is safer for real files. Reading them line by line with BufferedReader pairs well with such a library.

Summarize this post with: