STRING INSTANCE METHODS
Java String split() method
split() divides a string around a regular expression, or regex, and returns the parts in a String[] array. Matching separators are not included in the result, and the original string stays unchanged. An additional parameter controls the number of parts and trailing empty entries.
Splitting a string on commas
String tekstas = "Java,Quest,21";
String[] dalys = tekstas.split(",");
System.out.println(dalys.length);
for (String dalis : dalys) {
System.out.println(dalis);
}3
Java
Quest
21
- The variable
tekstasstores the text Java,Quest,21. - The argument
","supplies the splitting rule. In this regex, a comma means a literal comma. - The two commas separate three parts. They are stored in
dalysin their original order. dalys.lengthgives the number of elements, and the loop prints each part on its own line.
The result is an array, so System.out.println(dalys) alone would not display its element contents. Use a loop or, as demonstrated below, Arrays.toString().
Why is split() an instance method?
split() is called on the string to divide. That string is the receiver, while the splitting rule is supplied as an argument.
String[] dalys = tekstas.split(",");
We do not write String.split(...), because this is not a static method. Save or use the returned array; the original string does not automatically become an array.
Method syntax
public String[] split(String regex)
public String[] split(String regex, int limit)
| Part | Meaning |
|---|---|
regex | The separator pattern, supplied as a String. It can describe several different separators. |
limit | int parameter controlling the split limit and trailing empty parts. |
| Return type | String[] – an array of string parts. |
| Possible errors | PatternSyntaxException for an invalid regex or NullPointerException for a null reference. |
| Java version | Both overloads are available since Java 1.4. |
The call split(regex) behaves like split(regex, 0). This matters because zero discards empty entries at the end of the result.
Array elements and the unchanged original string
String tekstas = "Java:Quest";
String[] dalys = tekstas.split(":");
System.out.println(dalys[0]);
System.out.println(dalys[1]);
System.out.println(tekstas);Java
Quest
Java:Quest
Array indices start at 0. The first element here is Java, and the second is Quest. The original string remains Java:Quest because splitting does not modify it.
Array size uses the field length without parentheses. Check that an index exists before accessing it: not every input has the number of parts you expect.
Repeated spaces and tabs
import java.util.Arrays;
String tekstas = " Java Quest\t21 ";
String[] dalys = tekstas.trim().split("\\s+");
System.out.println(Arrays.toString(dalys));[Java, Quest, 21]
trim()removes the leading and trailing spaces in this string.- The regex
\srecognizes whitespace, including a space and a tab. The quantifier+allows one or more consecutive occurrences. - In Java source, write the regex as
"\\s+": two source backslashes preserve one in the string passed to the method. Arrays.toString(dalys)displays the array with square brackets and commas.
This input uses ordinary spaces and a tab. Under the default rules, the regex \s does not cover all Unicode whitespace characters.
Several separator types in one regex
import java.util.Arrays;
String tekstas = "Java,Quest;21|ready";
System.out.println(Arrays.toString(tekstas.split("[,;|]")));[Java, Quest, 21, ready]
The character class [,;|] matches one of three characters: a comma, a semicolon, or a vertical bar. Inside this class, the vertical bar is a literal character.
Separators are removed, and the parts retain their original order. Adding + after the class would treat consecutive separators as one match. Below, we will see why this matters for empty parts.
Literal dots and special regex symbols
import java.util.Arrays;
String adresas = "java.quest.lt";
System.out.println(Arrays.toString(adresas.split("\\.")));[java, quest, lt]
- The regex
\.matches a literal dot. In a Java string literal, it is written as"\\.". - The two dots separate three parts: java, quest, and lt.
- The plain regex
"."would match any character except line terminators by default. It is unsuitable when only a dot should separate the parts.
A separator from a variable: Pattern.quote()
import java.util.Arrays;
import java.util.regex.Pattern;
String tekstas = "Java|Quest|21";
String skirtukas = "|";
String[] dalys = tekstas.split(Pattern.quote(skirtukas));
System.out.println(Arrays.toString(dalys));[Java, Quest, 21]
Outside a character class, a vertical bar has a special regex meaning. Pattern.quote(skirtukas) prepares the variable’s value as a literal pattern, so actual bars separate the parts.
This is also useful for separators containing several characters. You do not need to escape their symbols manually.
How does the limit parameter work?
| Condition | Behavior |
|---|---|
limit > 0 | At most limit elements. The separator is applied at most limit - 1 times, and the last element contains the entire remaining text. |
limit = 0 | All matches are used, but trailing empty entries are discarded. |
limit < 0 | All matches are used, and trailing empty entries are preserved. |
A positive limit sets the maximum number of array elements. It does not guarantee that many elements. Zero and negative values are valid arguments, not errors.
A positive limit leaves the remainder in the last part
import java.util.Arrays;
String tekstas = "key=Java=Quest";
System.out.println(Arrays.toString(tekstas.split("=", 2)));
System.out.println(Arrays.toString(tekstas.split("=", 1)));[key, Java=Quest]
[key=Java=Quest]
- With a limit of
2, at most one split is performed. The first element is key, and the second holds the entire remainder Java=Quest. - With a limit of
1, the separator is not applied: the single element contains the whole string. - The last element can still contain separators. This is the intended behavior of a positive limit.
Trailing empty parts: the default and a negative limit
String tekstas = "Java,Quest,,";
System.out.println(tekstas.split(",").length);
System.out.println(tekstas.split(",", 0).length);
String[] visosDalys = tekstas.split(",", -1);
System.out.println(visosDalys.length);
for (String dalis : visosDalys) {
System.out.println("[" + dalis + "]");
}2
2
4
[Java]
[Quest]
[]
[]
Two commas follow Quest, giving two additional empty parts. The default overload and an explicit 0 discard them, so both arrays contain 2 elements.
A negative -1 preserves all parts, giving four elements. The brackets around each element reveal its content: the final two [] lines represent empty strings.
Any negative limit preserves trailing empty parts. It does not specify a count of elements from the end.
Leading and adjacent separators
String[] dalys = ",Java,,Quest,".split(",");
System.out.println(dalys.length);
for (String dalis : dalys) {
System.out.println("[" + dalis + "]");
}4
[]
[Java]
[]
[Quest]
The first comma is at the beginning, so it produces an empty element before it. The adjacent commas in the middle leave another empty part between them.
Only the trailing empty part is discarded by the default zero limit. Leading and internal empty parts remain. The regex ",+" would combine adjacent commas into one separator match and change the result.
Practical example: record fields and a missing value
String irasas = "JavaQuest;21;";
String[] laukai = irasas.split(";", -1);
if (laukai.length == 3) {
System.out.println(laukai[0]);
System.out.println(laukai[1]);
System.out.println("[" + laukai[2] + "]");
} else {
System.out.println(false);
}JavaQuest
21
[]
- The agreed format has three fields. The last field is missing, but its position must be preserved.
- The limit
-1preserves the empty final field. Without it, the default result would contain only two elements. - We check
laukai.length == 3before accessing the three indices. The number is still stored as text; splitting does not parse it.
This example suits a simple agreed format. CSV records with quoted values, separators within fields, or multiline values require a parser designed for that format.
No matches and an empty input string
String[] viena = "Java".split(",");
System.out.println(viena.length);
System.out.println("[" + viena[0] + "]");
String[] tuscia = "".split(",");
System.out.println(tuscia.length);
System.out.println("[" + tuscia[0] + "]");
System.out.println(",,".split(",").length);1
[Java]
1
[]
0
When the regex matches no part of the input, the result is a one-element array containing the original string. The first array therefore contains Java, and the second contains one empty string.
In the final call, the input consists only of separators. All resulting parts are empty, and the zero limit discards them, so the array length is 0.
One empty element is different from an array with no elements. Arrays.toString() can display [] for both, so check the length when the result is ambiguous.
An empty regex and a zero-width match at the start
import java.util.Arrays;
String[] dalys = "Java".split("");
System.out.println(dalys.length);
System.out.println(Arrays.toString(dalys));4
[J, a, v, a]
An empty regex "" can match without consuming characters. A match of this kind at the beginning does not create a leading empty element. This differs from the earlier example with an actual leading comma.
This string produces four separate letters. However, an empty regex is not a reliable way to split every user-visible Unicode character: emoji and composite characters, for example, can consist of multiple units.
Relationship to String.join() and retaining separators
String[] dalys = "Java,Quest,21".split(",");
String rezultatas = String.join(" / ", dalys);
System.out.println(rezultatas);Java / Quest / 21
split() produces an array of parts from one string, while String.join() combines parts using a chosen separator. Here, spaces and slashes take the place of the commas.
Splitting and joining do not always recover the original: default splitting can discard trailing empty parts, and several different separator types can be matched by one pattern.
Ordinary split() does not return the separators themselves, even if the regex has capturing groups. When both parts and matched separators are needed, Java 21 and later provide splitWithDelimiters().
An invalid regex throws PatternSyntaxException
String tekstas = "Java,Quest";
String[] dalys = tekstas.split("[,");
System.out.println(dalys.length);PatternSyntaxException
The expression [, begins a character class but omits the closing bracket. Java cannot compile the separator pattern and throws PatternSyntaxException. The array assignment does not complete, so the print statement is never reached.
The separator rule and the receiver must not be null
String tekstas = "Java,Quest";
String regex = null;
String[] dalys = tekstas.split(regex);
System.out.println(dalys.length);NullPointerException
The regex here is null, so there is no separator rule and the call throws NullPointerException. An empty regex "" is an actual string and behaves differently.
The method cannot be called on a null string reference either. An empty input string is a valid object whose behavior we covered above.
Common mistakes
- Expecting a single string even though
split()returns an array. - Printing the array directly instead of displaying its elements.
- Treating a dot or vertical bar as a literal regex separator without accounting for its special meaning.
- Interpreting a positive
limitas the number of splits rather than the maximum number of parts. - Forgetting that the default overload removes trailing empty parts.
- Accessing an array element without checking whether the input produced enough parts.
When should you use split()?
Use split() when a clear rule separates the parts: commas, whitespace, several separator types, or an agreed field format. Choose a limit for the task: positive to cap the number of parts, negative to preserve trailing empty values.
For a separator supplied by a variable, use Pattern.quote() when the value should be treated literally. Use a dedicated parser for a more complex file or data format.