Java
String Split Method
Empty Values
Programming
Data Handling

Java String.split() drops trailing empty strings (use limit -1)

Codemia Knowledge Hub ·

String.split() does not remove all empty values. The one-argument form removes only trailing empty strings from the result; empty strings in the middle are kept. To keep trailing empty values too, pass -1 as the second argument: split(delimiter, -1).

java
1String input = "a,b,,";
2
3String[] defaultSplit = input.split(",");
4// Result: ["a", "b"]  -- trailing empties dropped
5
6String[] keepAll = input.split(",", -1);
7// Result: ["a", "b", "", ""]  -- trailing empties preserved

This catches many developers off guard when parsing delimited data where empty fields carry meaning.

How the limit parameter works

split has two overloads:

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

The one-argument form behaves as if you passed limit = 0. The limit controls how many times the pattern is applied and whether trailing empty strings are kept.

Limit ValuePattern ApplicationsTrailing Empty Strings
0 (default)UnlimitedRemoved
-1UnlimitedPreserved
n > 0At most n - 1 timesPreserved

Default behavior (limit = 0)

java
"a,b,,".split(",")
// Splits into: ["a", "b", "", ""]
// Trailing empties removed: ["a", "b"]

Negative limit (limit = -1)

java
"a,b,,".split(",", -1)
// Splits into: ["a", "b", "", ""]
// Trailing empties preserved: ["a", "b", "", ""]

Positive limit (limit = 3)

java
"a,b,c,d".split(",", 3)
// Splits at most 2 times: ["a", "b", "c,d"]
// The remainder stays in the last element

Middle empty values are always kept

Only trailing empty strings are affected by the default limit. Empty strings between non-empty values survive either way:

java
1"a,,b".split(",")
2// Result: ["a", "", "b"]  -- middle empty preserved
3
4"a,,b,,".split(",")
5// Result: ["a", "", "b"]  -- middle empty preserved, trailing empties dropped

This asymmetry is the root of most confusion: people expect every empty field to be treated the same, but only trailing ones are dropped.

The delimiter is a regular expression

split() treats its first argument as a regex, not a plain string, so characters with special meaning must be escaped. Splitting on an unescaped . matches every character and produces an empty array, because every element is a trailing empty string:

java
1// WRONG: "." matches any character
2"api.v1.example".split(".")
3// Result: []  -- splits on every character, all trailing empties removed
4
5// CORRECT: escape the dot
6"api.v1.example".split("\\.")
7// Result: ["api", "v1", "example"]

Characters that need escaping in regex: ., |, *, +, ?, (, ), [, ], {, }, ^, $, \.

Pattern.quote for dynamic delimiters

When the delimiter comes from user input or configuration, hand-escaping is error-prone. Pattern.quote() treats any string as a literal:

java
1import java.util.regex.Pattern;
2
3String delimiter = "|";  // pipe is a regex alternation operator
4String input = "a|b|c";
5
6// WRONG: splits on empty string alternation
7String[] wrong = input.split(delimiter);
8
9// CORRECT: treats "|" as a literal character
10String[] correct = input.split(Pattern.quote(delimiter), -1);
11// Result: ["a", "b", "c"]

Where trailing empties matter

Parsing delimited rows

In pipe- or tab-delimited exports, a trailing empty field is real data, such as a nullable column with no value. The default split drops it, so code that reads fields by position gets fewer elements than expected and can throw ArrayIndexOutOfBoundsException.

java
1// TSV row with empty last field (nullable column)
2String row = "John\tDoe\t30\t";
3
4String[] defaultParts = row.split("\t");
5// Result: ["John", "Doe", "30"]  -- 3 fields, lost the empty 4th
6
7String[] allParts = row.split("\t", -1);
8// Result: ["John", "Doe", "30", ""]  -- 4 fields, correct

Splitting configuration values

A positive limit keeps everything after the first = together, so an = inside the value does not cause another split:

java
1String config = "host=db.example.com=extra";
2
3// Limit to 2 to keep everything after the first "=" together
4String[] parts = config.split("=", 2);
5// Result: ["host", "db.example.com=extra"]

Counting segments

java
1// Count how many segments a path has
2String path = "/usr/local/bin/";
3int segments = path.split("/", -1).length;
4// Result: 5 (["", "usr", "local", "bin", ""])
5// Without -1: 4 (trailing empty dropped)

split vs. StringTokenizer vs. Guava Splitter

FeatureString.split()StringTokenizerGuava Splitter
Trailing emptiesDropped by defaultAlways droppedConfigurable
Regex supportYesNoOptional
Empty token handlingMiddle preservedAlways droppedConfigurable
Return typeString[]EnumerationIterable<String>
Thread-safeYes (immutable)NoYes (immutable)

Guava's Splitter gives the most explicit control over empty values:

java
1import com.google.common.base.Splitter;
2
3List<String> parts = Splitter.on(',')
4    .splitToList("a,b,,");
5// Result: ["a", "b", "", ""]
6
7List<String> trimmed = Splitter.on(',')
8    .omitEmptyStrings()
9    .trimResults()
10    .splitToList("a, b, , ");
11// Result: ["a", "b"]

When to use a real parser instead

split() works for simple delimited data where fields never contain the delimiter. It breaks when the format supports quoting or escaping:

java
1// This CSV line has a quoted field containing a comma
2String csvLine = "\"Smith, John\",42,Engineer";
3
4// split on comma breaks the quoted field
5String[] parts = csvLine.split(",");
6// Result: ["\"Smith", " John\"", "42", "Engineer"]  -- wrong

For CSV, TSV with quoting, multiline fields or any structured text format, use a dedicated parser such as OpenCSV, Apache Commons CSV or Jackson CSV. split() is not a format parser.

Also validate the number of fields when you split user input with split(delimiter, -1). Code that assumes a fixed field count can introduce injection risks.


Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms