---
description: This tutorial covers the split() string method in java definitions, How to split string in java with a delimiter, Split string with regex and length, and split with space.
title: Java String split() Method with Example
image: https://www.guru99.com/images/java-string-split-method.png
---

[Skip to content](#main)

**⚡ 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.

Read More

![Java String split() Method](https://www.guru99.com/images/java-string-split-method.png)

## What is split() string in Java?

The `split()` method allows you to break a [string](https://www.guru99.com/java-strings.html) 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 ]()](https://www.guru99.com/images/uploads/2012/08/SplitString.png)

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.

**Don't Miss:**

- [Java Swing Tutorial: How to Create a GUI Application in Java](https://www.guru99.com/java-swing-gui.html)
- [Scala Tutorial](https://www.guru99.com/scala-tutorial.html)
- [Selection Sorting in Java Program with Example](https://www.guru99.com/selection-sorting-java.html)
- [Top 50 JDBC Interview Questions and Answers (2026)](https://www.guru99.com/jdbc-interview-questions.html)

## 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](https://www.guru99.com/java-variables.html) 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.

This code is editable. Click Run to Compile + Execute  

![]()

 

## 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](https://www.guru99.com/java-arrays.html) 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

🔀 How do you split on more than one delimiter at once?

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

📋 Can split() results be turned into a List?

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.

🤖 Can AI write the regex for a tricky split?

Yes. [AI](https://www.guru99.com/ai-tutorial.html) 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.

🧠 How does AI help when split() returns the wrong count?

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.

📄 Is split() suitable for parsing CSV files?

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](https://www.guru99.com/buffered-reader-in-java.html) pairs well with such a library.

#### Summarize this post with:

ChatGPTPerplexityGrokGoogle AI

**Stay Updated on AI** **Get Weekly AI Skills, Trends, Actionable Advice.**

##### Sign up for the newsletter

Subscribe for Free

You have successfully subscribed.  
Please check your inbox.

![AI-Newsletter]() Chosen by over **350,000+** professionals

[Scroll to top](#wrapper)

×

Search for:

```json
{"@context":"https://schema.org","@graph":[{"@type":"Organization","@id":"https://www.guru99.com/#organization","name":"Guru99","sameAs":["https://www.facebook.com/Guru99Official","https://twitter.com/guru99com"],"logo":{"@type":"ImageObject","@id":"https://www.guru99.com/#logo","url":"https://www.guru99.com/images/guru99-logo-v1-150x59.png","contentUrl":"https://www.guru99.com/images/guru99-logo-v1-150x59.png","caption":"Guru99","inLanguage":"en-US"}},{"@type":"WebSite","@id":"https://www.guru99.com/#website","url":"https://www.guru99.com","name":"Guru99","publisher":{"@id":"https://www.guru99.com/#organization"},"inLanguage":"en-US"},{"@type":"ImageObject","@id":"https://www.guru99.com/images/java-string-split-method.png","url":"https://www.guru99.com/images/java-string-split-method.png","width":"700","height":"250","caption":"Java String split() Method","inLanguage":"en-US"},{"@type":"BreadcrumbList","@id":"https://www.guru99.com/how-to-split-a-string-in-java.html#breadcrumb","itemListElement":[{"@type":"ListItem","position":"1","item":{"@id":"https://www.guru99.com","name":"Home"}},{"@type":"ListItem","position":"2","item":{"@id":"https://www.guru99.com/java-tutorials","name":"Java Tutorials"}},{"@type":"ListItem","position":"3","item":{"@id":"https://www.guru99.com/how-to-split-a-string-in-java.html","name":"Java String split() Method with Example"}}]},{"@type":"WebPage","@id":"https://www.guru99.com/how-to-split-a-string-in-java.html#webpage","url":"https://www.guru99.com/how-to-split-a-string-in-java.html","name":"Java String split() Method with Example","dateModified":"2026-10-01T12:33:23+05:30","isPartOf":{"@id":"https://www.guru99.com/#website"},"primaryImageOfPage":{"@id":"https://www.guru99.com/images/java-string-split-method.png"},"inLanguage":"en-US","breadcrumb":{"@id":"https://www.guru99.com/how-to-split-a-string-in-java.html#breadcrumb"}},{"@type":"Person","@id":"https://www.guru99.com/author/editorial","name":"Editorial Team","url":"https://www.guru99.com/author/editorial","image":{"@type":"ImageObject","@id":"https://www.guru99.com/images/favicon-new-logo.png","url":"https://www.guru99.com/images/favicon-new-logo.png","caption":"Editorial Team","inLanguage":"en-US"},"sameAs":["https://www.guru99.com/editorial-team"],"worksFor":{"@id":"https://www.guru99.com/#organization"}},{"articleSection":"Java Tutorials","headline":"Java String split() Method with Example","description":"This tutorial covers the split() string method in java definitions, How to split string in java with a delimiter, Split string with regex and length, and split with space.","keywords":"java","speakable":{"@type":"SpeakableSpecification","cssSelector":[".entry-title",".summary"]},"@type":"Article","author":{"@id":"https://www.guru99.com/author/editorial","name":"Editorial Team"},"dateModified":"2026-10-01T12:33:23+05:30","image":{"@id":"https://www.guru99.com/images/java-string-split-method.png"},"copyrightYear":"2026","name":"Java String split() Method with Example","subjectOf":[{"@type":"FAQPage","mainEntity":[{"@type":"Question","name":"How do you split on more than one delimiter at once?","acceptedAnswer":{"@type":"Answer","text":"Use a character class, as in split(\"[,;]\"), which breaks on either a comma or a semicolon. Alternation also works: split(\",|;\")."}},{"@type":"Question","name":"Can split() results be turned into a List?","acceptedAnswer":{"@type":"Answer","text":"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."}},{"@type":"Question","name":"Can AI write the regex for a tricky split?","acceptedAnswer":{"@type":"Answer","text":"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."}},{"@type":"Question","name":"How does AI help when split() returns the wrong count?","acceptedAnswer":{"@type":"Answer","text":"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."}},{"@type":"Question","name":"Is split() suitable for parsing CSV files?","acceptedAnswer":{"@type":"Answer","text":"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."}}]}],"@id":"https://www.guru99.com/how-to-split-a-string-in-java.html#schema-1156501","isPartOf":{"@id":"https://www.guru99.com/how-to-split-a-string-in-java.html#webpage"},"publisher":{"@id":"https://www.guru99.com/#organization"},"inLanguage":"en-US","mainEntityOfPage":{"@id":"https://www.guru99.com/how-to-split-a-string-in-java.html#webpage"}}]}
```
